FOSSology  4.5.0-rc1
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  '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  $vars['licenseDBHealth'] = $this->checkLicenseDBHealth();
85  }
86  if ($request->isMethod('POST')) {
87  if ($request->get('importFrom') === 'licensedb') {
88  $startTime = microtime(true);
89  $vars['message'] = $this->handleLicenseDbImport();
90  $fetchLicenseTime = microtime(true) - $startTime;
91  $this->fileLogger->debug("Fetching License and Check if exist took: " . sprintf("%0.3fms", 1000 * $fetchLicenseTime));
92  $this->fileLogger->debug("****************** Message From LicenseDB import [" . date('Y-m-d H:i:s') . "] ******************");
93  $this->fileLogger->debug($vars["message"]);
94  $this->fileLogger->debug("****************** End Message From LicenseDB import ******************");
95  } else {
96  $uploadFile = $request->files->get(self::FILE_INPUT_NAME);
97  $delimiter = $request->get('delimiter') ?: ',';
98  $enclosure = $request->get('enclosure') ?: '"';
99  $vars['message'] = $this->handleFileUpload($uploadFile, $delimiter,
100  $enclosure)[1];
101  }
102  }
103  $vars[self::KEY_UPLOAD_MAX_FILESIZE] = ini_get(self::KEY_UPLOAD_MAX_FILESIZE);
104  $vars['baseUrl'] = $request->getBaseUrl();
105  $vars['license_csv_import'] = true;
106 
107  if (!empty(trim($this->configuration['url']))) {
108  $vars['baseURL'] = !empty($this->configuration['uri']);
109  $vars['authToken'] = !empty($this->configuration['token']);
110  $vars['exportEndpoint'] = !empty($this->configuration['content']);
111  return $this->render("admin_license_from_licensedb.html.twig", $this->mergeWithDefault($vars));
112  } else {
113  return $this->render("admin_license_from_csv.html.twig", $this->mergeWithDefault($vars));
114  }
115  }
116 
124  public function handleLicenseDbImport()
125  {
126  $msg = '<br>';
127  $data = null;
128  $finalURL = $this->configuration['url'] . $this->configuration['uri'] . $this->configuration['content'];
129  try {
130  $startTimeReq = microtime(true);
131  $response = $this->guzzleClient->get($finalURL);
132  $fetchLicenseTimeReq = microtime(true) - $startTimeReq;
133  $this->fileLogger->debug("LicenseDB req:' took " . sprintf("%0.3fms", 1000 * $fetchLicenseTimeReq));
134  if ($response->getStatusCode() == 200) {
135  $data = json_decode($response->getBody()->getContents());
136  }
137 
138  if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
139  return $msg . "Error decoding JSON: " . json_last_error_msg() . "\n";
140  } else {
141  return $this->licenseCsvImport->importJsonData($data, $msg);
142  }
143  } catch (RequestException|GuzzleException $e) {
144  return $msg . _('Something Went Wrong, check if host is accessible') . ': ' . $e->getMessage();
145  }
146  }
147 
152  public function handleFileUpload($uploadedFile, $delimiter = ',', $enclosure = '"')
153  {
154  $errMsg = '';
155  if (!($uploadedFile instanceof UploadedFile)) {
156  $errMsg = _("No file selected");
157  } elseif ($uploadedFile->getError() !== UPLOAD_ERR_OK) {
158  $errMsg = $uploadedFile->getErrorMessage();
159  } elseif ($uploadedFile->getSize() == 0 && $uploadedFile->getError() == 0) {
160  $errMsg = _("Larger than upload_max_filesize ") .
161  ini_get(self::KEY_UPLOAD_MAX_FILESIZE);
162  } elseif ($uploadedFile->getClientOriginalExtension() != 'csv'
163  && $uploadedFile->getClientOriginalExtension() != 'json') {
164  $errMsg = _('Invalid file extension ') .
165  $uploadedFile->getClientOriginalExtension() . ' of file ' .
166  $uploadedFile->getClientOriginalName();
167  }
168  if (!empty($errMsg)) {
169  return array(false, $errMsg, 400);
170  }
171  $this->licenseCsvImport->setDelimiter($delimiter);
172  $this->licenseCsvImport->setEnclosure($enclosure);
173 
174  return array(true, $this->licenseCsvImport->handleFile($uploadedFile->getRealPath(), $uploadedFile->getClientOriginalExtension()), 200);
175  }
176 
177 
185  public function checkLicenseDBHealth()
186  {
187 
188  $getHealth = $this->configuration['url'] . $this->configuration['uri'] . "/health";
189  try {
190  $response = $this->guzzleClient->get($getHealth);
191  if ($response->getStatusCode() === 200) {
192  return true;
193  }
194  } catch (RequestException|GuzzleException $e) {
195  return false;
196  }
197 
198  return false;
199  }
200 }
201 
202 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