FOSSology  4.5.1
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 
17 use GuzzleHttp\Client;
18 use GuzzleHttp\Exception\GuzzleException;
19 use GuzzleHttp\Exception\RequestException;
20 use Symfony\Component\HttpFoundation\File\UploadedFile;
21 use Symfony\Component\HttpFoundation\Request;
22 use Symfony\Component\HttpFoundation\Response;
23 
28 {
29  const NAME = "admin_license_from_csv";
30  const KEY_UPLOAD_MAX_FILESIZE = 'upload_max_filesize';
31  const FILE_INPUT_NAME = 'file_input';
32  const FILE_INPUT_NAME_V2 = 'fileInput';
33 
37  private $guzzleClient;
41  private $sysconfig;
42 
43  function __construct()
44  {
45  global $SysConf;
46  parent::__construct(self::NAME, array(
47  self::TITLE => "Admin License Import",
48  self::MENU_LIST => "Admin::License Admin::License Import",
49  self::REQUIRES_LOGIN => true,
50  self::PERMISSION => Auth::PERM_ADMIN
51  ));
53  $this->licenseCsvImport = $GLOBALS['container']->get('app.license_csv_import');
54  $this->sysconfig = $SysConf['SYSCONFIG'];
55  $this->configuration = [
56  'url' => trim($this->sysconfig['LicenseDBURL']),
57  'uri' => trim($this->sysconfig['LicenseDBBaseURL']),
58  'content' => trim($this->sysconfig['LicenseDBContent']),
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  $getHealth = $this->configuration['url'] . $this->configuration['uri'] . "/health";
86  $vars['licenseDBHealth'] = HttpUtils::checkLicenseDBHealth($getHealth, $this->guzzleClient);
87  }
88  if ($request->isMethod('POST')) {
89  if ($request->get('importFrom') === 'licensedb') {
90  $startTime = microtime(true);
91  $vars['message'] = $this->handleLicenseDbImport();
92  $fetchLicenseTime = microtime(true) - $startTime;
93  $this->fileLogger->debug("Fetching License and Check if exist took: " . sprintf("%0.3fms", 1000 * $fetchLicenseTime));
94  $this->fileLogger->debug("****************** Message From LicenseDB import [" . date('Y-m-d H:i:s') . "] ******************");
95  $this->fileLogger->debug($vars["message"]);
96  $this->fileLogger->debug("****************** End Message From LicenseDB import ******************");
97  } else {
98  $uploadFile = $request->files->get(self::FILE_INPUT_NAME);
99  $delimiter = $request->get('delimiter') ?: ',';
100  $enclosure = $request->get('enclosure') ?: '"';
101  $vars['message'] = $this->handleFileUpload($uploadFile, $delimiter,
102  $enclosure)[1];
103  }
104  }
105  $vars[self::KEY_UPLOAD_MAX_FILESIZE] = ini_get(self::KEY_UPLOAD_MAX_FILESIZE);
106  $vars['baseUrl'] = $request->getBaseUrl();
107  $vars['license_csv_import'] = true;
108 
109  if (!empty(trim($this->configuration['url']))) {
110  $vars['baseURL'] = !empty($this->configuration['uri']);
111  $vars['authToken'] = !empty($this->configuration['token']);
112  $vars['exportEndpoint'] = !empty($this->configuration['content']);
113  return $this->render("admin_license_from_licensedb.html.twig", $this->mergeWithDefault($vars));
114  } else {
115  return $this->render("admin_license_from_csv.html.twig", $this->mergeWithDefault($vars));
116  }
117  }
118 
126  public function handleLicenseDbImport()
127  {
128  $msg = '<br>';
129  $data = null;
130  $finalURL = $this->configuration['url'] . $this->configuration['uri'] . $this->configuration['content'];
131  try {
132  $startTimeReq = microtime(true);
133  $response = $this->guzzleClient->get($finalURL);
134  $fetchLicenseTimeReq = microtime(true) - $startTimeReq;
135  $this->fileLogger->debug("LicenseDB req:' took " . sprintf("%0.3fms", 1000 * $fetchLicenseTimeReq));
136 
137  $data = HttpUtils::processHttpResponse($response);
138  return $this->licenseCsvImport->importJsonData($data, $msg);
139  } catch (HttpClientException $e) {
140  return $msg . $e->getMessage();
141  } catch (RequestException|GuzzleException $e) {
142  return $msg . _('Something Went Wrong, check if host is accessible') . ': ' . $e->getMessage();
143  }
144  }
145 
150  public function handleFileUpload($uploadedFile, $delimiter = ',', $enclosure = '"')
151  {
152  $errMsg = '';
153  if (!($uploadedFile instanceof UploadedFile)) {
154  $errMsg = _("No file selected");
155  } elseif ($uploadedFile->getError() !== UPLOAD_ERR_OK) {
156  $errMsg = $uploadedFile->getErrorMessage();
157  } elseif ($uploadedFile->getSize() == 0 && $uploadedFile->getError() == 0) {
158  $errMsg = _("Larger than upload_max_filesize ") .
159  ini_get(self::KEY_UPLOAD_MAX_FILESIZE);
160  } elseif ($uploadedFile->getClientOriginalExtension() != 'csv'
161  && $uploadedFile->getClientOriginalExtension() != 'json') {
162  $errMsg = _('Invalid file extension ') .
163  $uploadedFile->getClientOriginalExtension() . ' of file ' .
164  $uploadedFile->getClientOriginalName();
165  }
166  if (!empty($errMsg)) {
167  return array(false, $errMsg, 400);
168  }
169  $this->licenseCsvImport->setDelimiter($delimiter);
170  $this->licenseCsvImport->setEnclosure($enclosure);
171 
172  return array(true, $this->licenseCsvImport->handleFile($uploadedFile->getRealPath(), $uploadedFile->getClientOriginalExtension()), 200);
173  }
174 }
175 
176 register_plugin(new AdminLicenseFromCSV());
Contains the constants and helpers for authentication of user.
Definition: Auth.php:24
Exception when Guzzle client response is not as expected.
render($templateName, $vars=null, $headers=null)
static processHttpResponse($response)
Definition: HttpUtils.php:89
static getGuzzleClient(array $SysConf, string $baseUri, string $token="")
Definition: HttpUtils.php:25
static checkLicenseDBHealth(string $getHealth, $guzzleClient)
Definition: HttpUtils.php:62
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