FOSSology  4.7.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 
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_obligation_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 Obligation Import",
50  self::MENU_LIST => "Admin::Obligation Admin::Obligation Import",
51  self::REQUIRES_LOGIN => true,
52  self::PERMISSION => Auth::PERM_ADMIN
53  ));
55  $this->obligationsCsvImport = $GLOBALS['container']->get('app.obligation_csv_import');
56  $this->sysconfig = $SysConf;
57  $this->configuration = [
58  'uri' => trim($this->sysconfig['SYSCONFIG']['LicenseDBBaseURL']),
59  'content' => trim($this->sysconfig['SYSCONFIG']['LicenseDBContentObligations']),
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']['OidcM2MAppId']),
67  "clientSecret" => trim($this->sysconfig['SYSCONFIG']['OidcM2MSecret']),
68  "urlAuthorize" => trim($this->sysconfig['SYSCONFIG']['OidcM2MAuthorizeURL']),
69  "urlAccessToken" => trim($this->sysconfig['SYSCONFIG']['OidcM2MAccessTokenURL']),
70  "urlResourceOwnerDetails" => trim($this->sysconfig['SYSCONFIG']['OidcM2MResourceOwnerURL']),
71  ]);
72 
73  if (isset($this->sysconfig['SYSCONFIG']['OidcM2MScope'])) {
74  $this->configuration['scope'] = trim($this->sysconfig['SYSCONFIG']['OidcM2MScope']);
75  }
76  } else {
77  $this->oidcProvider = null;
78  }
79  }
80 
84  public function getFileInputName($apiVersion = ApiVersion::V1)
85  {
86  if ($apiVersion == ApiVersion::V2) {
87  return $this::FILE_INPUT_NAME_V2;
88  } else {
89  return $this::FILE_INPUT_NAME;
90  }
91  }
92 
97  protected function handle(Request $request)
98  {
99  $vars = array();
100  if (!$request->isMethod('POST')) {
101  $getHealth = $this->configuration['uri'] . $this->configuration['health'];
102  $guzzleClient = HttpUtils::getGuzzleClient($this->sysconfig, $this->configuration['uri']);
103  $vars['licenseDBHealth'] = HttpUtils::checkLicenseDBHealth($getHealth, $guzzleClient);
104  }
105  if ($request->isMethod('POST')) {
106  if ($request->get('importFrom') === 'licensedb') {
107  $startTime = microtime(true);
108  $vars['message'] = $this->handleLicenseDbObligationImport();
109  $fetchLicenseTime = microtime(true) - $startTime;
110  $this->fileLogger->debug("Fetching Obligations and Check time took: " . sprintf("%0.3fms", 1000 * $fetchLicenseTime));
111  $this->fileLogger->debug("****************** Message From LicenseDB import [" . date('Y-m-d H:i:s') . "] ******************");
112  $this->fileLogger->debug($vars["message"]);
113  $this->fileLogger->debug("****************** End Message From LicenseDB import ******************");
114  } else {
115  $uploadFile = $request->files->get(self::FILE_INPUT_NAME);
116  $delimiter = $request->get('delimiter') ?: ',';
117  $enclosure = $request->get('enclosure') ?: '"';
118  $result = $this->handleFileUpload($uploadFile, $delimiter, $enclosure);
119  $vars['message'] = is_array($result) ? $result[1] : $result;
120  }
121  }
122 
123  $vars[self::KEY_UPLOAD_MAX_FILESIZE] = ini_get(self::KEY_UPLOAD_MAX_FILESIZE);
124  $vars['baseUrl'] = $request->getBaseUrl();
125  $vars['license_csv_import'] = false;
126 
127  if (!empty(trim($this->configuration['uri']))) {
128  $vars['baseURL'] = !empty($this->configuration['uri']);
129  $vars['tokenConfig'] = !empty($this->configuration['token']) || $this->oidcProvider != null;
130  $vars['exportEndpoint'] = !empty($this->configuration['content']);
131  return $this->render("admin_license_from_licensedb.html.twig", $this->mergeWithDefault($vars));
132  } else {
133  return $this->render("admin_license_from_csv.html.twig", $this->mergeWithDefault($vars));
134  }
135  }
136 
145  {
146  $msg = '<br>';
147  $data = null;
148  $finalURL = $this->configuration['uri'] . $this->configuration['content'];
149  try {
150  $startTimeReq = microtime(true);
151 
152  $accessToken = null;
153  if ($this->configuration['token'] != null) {
154  $accessToken = $this->configuration['token'];
155  } else {
156  $options = [];
157  if (isset($this->configuration['scope'])) {
158  $options['scope'] = $this->configuration['scope'];
159  }
160  $accessToken = $this->oidcProvider->getAccessToken('client_credentials', $options);
161  }
162  $guzzleClient = HttpUtils::getGuzzleClient($this->sysconfig, $this->configuration['uri'], $accessToken);
163  $response = $guzzleClient->get($finalURL);
164  $fetchLicenseTimeReq = microtime(true) - $startTimeReq;
165  $this->fileLogger->debug("LicenseDB req:' took " . sprintf("%0.3fms", 1000 * $fetchLicenseTimeReq));
166 
167  $data = HttpUtils::processHttpResponse($response);
168  return $this->obligationsCsvImport->importJsonData($data, $msg);
169  } catch (HttpClientException $e) {
170  return $msg . $e->getMessage();
171  } catch (RequestException | GuzzleException $e) {
172  return $msg . _('Something Went Wrong, check if host is accessible') . ': ' . $e->getMessage();
173  }
174  }
175 
180  public function handleFileUpload($uploadedFile, $delimiter = ',', $enclosure = '"', $fromRest = false)
181  {
182  $errMsg = '';
183  if (!($uploadedFile instanceof UploadedFile)) {
184  $errMsg = _("No file selected");
185  } elseif ($uploadedFile->getSize() == 0 && $uploadedFile->getError() == 0) {
186  $errMsg = _("Larger than upload_max_filesize ") . ini_get(self::KEY_UPLOAD_MAX_FILESIZE);
187  } elseif (
188  $uploadedFile->getClientOriginalExtension() != 'csv'
189  && $uploadedFile->getClientOriginalExtension() != 'json'
190  ) {
191  $errMsg = _('Invalid extension ') .
192  $uploadedFile->getClientOriginalExtension() . ' of file ' .
193  $uploadedFile->getClientOriginalName();
194  }
195  if (!empty($errMsg)) {
196  if ($fromRest) {
197  return array(false, $errMsg, 400);
198  }
199  return $errMsg;
200  }
201  $this->obligationsCsvImport->setDelimiter($delimiter);
202  $this->obligationsCsvImport->setEnclosure($enclosure);
203 
204  return array(true, $this->obligationsCsvImport->handleFile($uploadedFile->getRealPath(), $uploadedFile->getClientOriginalExtension()), 200);
205  }
206 }
207 
208 register_plugin(new AdminObligationFromCSV());
Helper class for Obligation CSV Import.
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.
handleFileUpload($uploadedFile, $delimiter=',', $enclosure='"', $fromRest = false)
char * trim(char *ptext)
Trimming whitespace.
Definition: fossconfig.c:690
fo_conf * sysconfig