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 use League\OAuth2\Client\Provider\GenericProvider;
24 
29 {
30  const NAME = "admin_license_from_csv";
31  const KEY_UPLOAD_MAX_FILESIZE = 'upload_max_filesize';
32  const FILE_INPUT_NAME = 'file_input';
33  const FILE_INPUT_NAME_V2 = 'fileInput';
34 
38  private $oidcProvider;
39 
43  private $sysconfig;
44 
45  function __construct()
46  {
47  global $SysConf;
48  parent::__construct(self::NAME, array(
49  self::TITLE => "Admin License Import",
50  self::MENU_LIST => "Admin::License Admin::License Import",
51  self::REQUIRES_LOGIN => true,
52  self::PERMISSION => Auth::PERM_ADMIN
53  ));
55  $this->licenseCsvImport = $GLOBALS['container']->get('app.license_csv_import');
56  $this->sysconfig = $SysConf;
57  $this->configuration = [
58  'uri' => trim($this->sysconfig['SYSCONFIG']['LicenseDBBaseURL']),
59  'content' => trim($this->sysconfig['SYSCONFIG']['LicenseDBContent']),
60  'health' => trim($this->sysconfig['SYSCONFIG']['LicenseDBHealth']),
61  'token' => empty(trim($this->sysconfig['SYSCONFIG']['LicenseDBToken'])) ? null : trim($this->sysconfig['SYSCONFIG']['LicenseDBToken']),
62  ];
63 
64  if ($this->configuration['token'] == null) {
65  $this->oidcProvider = new GenericProvider([
66  "clientId" => trim($this->sysconfig['SYSCONFIG']['OidcAppId']),
67  "clientSecret" => trim($this->sysconfig['SYSCONFIG']['OidcSecret']),
68  "redirectUri" => trim($this->sysconfig['SYSCONFIG']['OidcRedirectURL']),
69  "urlAuthorize" => trim($this->sysconfig['SYSCONFIG']['OidcAuthorizeURL']),
70  "urlAccessToken" => trim($this->sysconfig['SYSCONFIG']['OidcAccessTokenURL']),
71  "urlResourceOwnerDetails" => trim($this->sysconfig['SYSCONFIG']['OidcResourceURL']),
72  ]);
73 
74  if (isset($this->sysconfig['SYSCONFIG']['OidcScope'])) {
75  $this->configuration['scope'] = trim($this->sysconfig['SYSCONFIG']['OidcScope']);
76  }
77  } else {
78  $this->oidcProvider = null;
79  }
80  }
81 
85  public function getFileInputName($apiVersion = ApiVersion::V1)
86  {
87  if ($apiVersion == ApiVersion::V2) {
88  return $this::FILE_INPUT_NAME_V2;
89  } else {
90  return $this::FILE_INPUT_NAME;
91  }
92  }
93 
98  protected function handle(Request $request)
99  {
100  $vars = array();
101  if (!$request->isMethod('POST')) {
102  $getHealth = $this->configuration['uri'] . $this->configuration['health'];
103  $guzzleClient = HttpUtils::getGuzzleClient($this->sysconfig, $this->configuration['uri']);
104  $vars['licenseDBHealth'] = HttpUtils::checkLicenseDBHealth($getHealth, $guzzleClient);
105  }
106  if ($request->isMethod('POST')) {
107  if ($request->get('importFrom') === 'licensedb') {
108  $startTime = microtime(true);
109  $vars['message'] = $this->handleLicenseDbImport();
110  $fetchLicenseTime = microtime(true) - $startTime;
111  $this->fileLogger->debug("Fetching License and Check if exist took: " . sprintf("%0.3fms", 1000 * $fetchLicenseTime));
112  $this->fileLogger->debug("****************** Message From LicenseDB import [" . date('Y-m-d H:i:s') . "] ******************");
113  $this->fileLogger->debug($vars["message"]);
114  $this->fileLogger->debug("****************** End Message From LicenseDB import ******************");
115  } else {
116  $uploadFile = $request->files->get(self::FILE_INPUT_NAME);
117  $delimiter = $request->get('delimiter') ?: ',';
118  $enclosure = $request->get('enclosure') ?: '"';
119  $vars['message'] = $this->handleFileUpload(
120  $uploadFile,
121  $delimiter,
122  $enclosure
123  )[1];
124  }
125  }
126  $vars[self::KEY_UPLOAD_MAX_FILESIZE] = ini_get(self::KEY_UPLOAD_MAX_FILESIZE);
127  $vars['baseUrl'] = $request->getBaseUrl();
128  $vars['license_csv_import'] = true;
129 
130  if (!empty(trim($this->configuration['uri']))) {
131  $vars['baseURL'] = !empty($this->configuration['uri']);
132  $vars['tokenConfig'] = !empty($this->configuration['token']) || $this->oidcProvider != null;
133  $vars['exportEndpoint'] = !empty($this->configuration['content']);
134  return $this->render("admin_license_from_licensedb.html.twig", $this->mergeWithDefault($vars));
135  } else {
136  return $this->render("admin_license_from_csv.html.twig", $this->mergeWithDefault($vars));
137  }
138  }
139 
147  public function handleLicenseDbImport()
148  {
149  $msg = '<br>';
150  $data = null;
151  $finalURL = $this->configuration['uri'] . $this->configuration['content'];
152  try {
153  $startTimeReq = microtime(true);
154 
155  $accessToken = null;
156  if ($this->configuration['token'] != null) {
157  $accessToken = $this->configuration['token'];
158  } else {
159  $options = [];
160  if (isset($this->configuration['scope'])) {
161  $options['scope'] = $this->configuration['scope'];
162  }
163  $accessToken = $this->oidcProvider->getAccessToken('client_credentials', $options);
164  }
165  $guzzleClient = HttpUtils::getGuzzleClient($this->sysconfig, $this->configuration['uri'], $accessToken);
166  $response = $guzzleClient->get($finalURL);
167  $fetchLicenseTimeReq = microtime(true) - $startTimeReq;
168 
169  $this->fileLogger->debug("LicenseDB req:' took " . sprintf("%0.3fms", 1000 * $fetchLicenseTimeReq));
170  $data = HttpUtils::processHttpResponse($response);
171  return $this->licenseCsvImport->importJsonData($data, $msg);
172  } catch (HttpClientException $e) {
173  return $msg . $e->getMessage();
174  } catch (RequestException | GuzzleException $e) {
175  return $msg . _('Something Went Wrong, check if host is accessible') . ': ' . $e->getMessage();
176  }
177  }
178 
183  public function handleFileUpload($uploadedFile, $delimiter = ',', $enclosure = '"')
184  {
185  $errMsg = '';
186  if (!($uploadedFile instanceof UploadedFile)) {
187  $errMsg = _("No file selected");
188  } elseif ($uploadedFile->getError() !== UPLOAD_ERR_OK) {
189  $errMsg = $uploadedFile->getErrorMessage();
190  } elseif ($uploadedFile->getSize() == 0 && $uploadedFile->getError() == 0) {
191  $errMsg = _("Larger than upload_max_filesize ") .
192  ini_get(self::KEY_UPLOAD_MAX_FILESIZE);
193  } elseif (
194  $uploadedFile->getClientOriginalExtension() != 'csv'
195  && $uploadedFile->getClientOriginalExtension() != 'json'
196  ) {
197  $errMsg = _('Invalid file extension ') .
198  $uploadedFile->getClientOriginalExtension() . ' of file ' .
199  $uploadedFile->getClientOriginalName();
200  }
201  if (!empty($errMsg)) {
202  return array(false, $errMsg, 400);
203  }
204  $this->licenseCsvImport->setDelimiter($delimiter);
205  $this->licenseCsvImport->setEnclosure($enclosure);
206 
207  return array(true, $this->licenseCsvImport->handleFile($uploadedFile->getRealPath(), $uploadedFile->getClientOriginalExtension()), 200);
208  }
209 }
210 
211 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