FOSSology  4.8.0-rc1
Open Source License Compliance by Open Source Software
admin-config.php
1 <?php
2 /*
3  SPDX-FileCopyrightText: © 2011-2013 Hewlett-Packard Development Company, L.P.
4 
5  SPDX-License-Identifier: GPL-2.0-only
6 */
7 
9 use GuzzleHttp\Client;
10 use GuzzleHttp\Exception\RequestException;
11 
12 define("TITLE_FOCONFIG", _("Configuration Variables"));
13 
18 class foconfig extends FO_Plugin
19 {
20  var $CreateAttempts = 0;
22  private $dbManager;
23 
24  function __construct()
25  {
26  $this->Name = "foconfig";
27  $this->Title = TITLE_FOCONFIG;
28  $this->MenuList = "Admin::Customize";
29  $this->DBaccess = PLUGIN_DB_ADMIN;
30  $this->PluginLevel = 50; // run before 'regular' plugins
31  parent::__construct();
32  $this->dbManager = $GLOBALS['container']->get('db.manager');
33  }
34 
38  function HTMLout()
39  {
40  global $PG_CONN;
41  $OutBuf="";
42 
43  /* get config rows from sysconfig table */
44  $sql = "select * from sysconfig order by group_name, group_order";
45  $result = pg_query($PG_CONN, $sql);
46  DBCheckResult($result, $sql, __FILE__, __LINE__);
47 
48  $Group = "";
49  $InputStyle = "style='background-color:#dbf0f7'";
50  $OutBuf .= '<style> table.myTable > tbody > tr:first-child > td:first-child{width:20%} </style>';
51  $OutBuf .= "<form method='POST'>";
52  while ($row = pg_fetch_assoc($result)) {
53  if ($Group != $row['group_name']) {
54  if ($Group) {
55  $OutBuf .= "</table><br>";
56  }
57  $Group = $row['group_name'];
58  $OutBuf .= '<table border=1 class="myTable table table-striped" style="border-collapse: unset;">';
59  }
60 
61  $OutBuf .= "<tr><td>$row[ui_label]</td><td>";
62  switch ($row['vartype']) {
63  case CONFIG_TYPE_INT:
64  case CONFIG_TYPE_TEXT:
65  $ConfVal = htmlentities($row['conf_value']);
66  $OutBuf .= "<INPUT type='text' name='new[$row[variablename]]' size='70' value='$ConfVal' title='$row[description]' $InputStyle>";
67  $OutBuf .= "<br>$row[description]";
68  break;
70  $ConfVal = htmlentities($row['conf_value']);
71  $OutBuf .= "<br><textarea name='new[$row[variablename]]' rows=3 cols=80 title='$row[description]' $InputStyle>$ConfVal</textarea>";
72  $OutBuf .= "<br>$row[description]";
73  break;
75  $ConfVal = htmlentities($row['conf_value']);
76  $OutBuf .= "<INPUT type='password' name='new[$row[variablename]]' size='70' value='$ConfVal' title='$row[description]' $InputStyle>";
77  $OutBuf .= "<br>$row[description]";
78  break;
79  case CONFIG_TYPE_DROP:
80  $ConfVal = htmlentities($row['conf_value']);
81  $Options = explode("|",$row['option_value']);
82  $OutBuf .= "<select name='new[$row[variablename]]' title='$row[description]' $InputStyle>";
83  foreach ($Options as $Option) {
84  $matches = array();
85  preg_match('/([ \\w]+)\\{(.*)\\}/', $Option, $matches);
86  $Option_display = $matches[1];
87  $Option_value = $matches[2];
88  $OutBuf .= "<option $InputStyle value='$Option_value' ";
89  if ($ConfVal == $Option_value) {
90  $OutBuf .= "selected";
91  }
92  $OutBuf .= ">$Option_display</option>";
93  }
94  $OutBuf .= "</select>";
95  $OutBuf .= "<br>$row[description]";
96  break;
97  case CONFIG_TYPE_BOOL:
98  $ConfVal = filter_var($row['conf_value'], FILTER_VALIDATE_BOOLEAN);
99  $checked = $ConfVal ? "checked" : "";
100  $ConfVal = $ConfVal ? "true" : "false";
101  $OutBuf .= "<input type='checkbox' name='new[" . $row['variablename'] .
102  "]' id='" . $row['variablename'] . "' value='true' title='" .
103  $row['description'] . "' $InputStyle $checked />";
104  $OutBuf .= "<label for='" . $row['variablename'] .
105  "'>" . $row['description'] . "</label>";
106  break;
108  $ConfVal = $row['conf_value'];
109  $selectedIds = array_map('trim', explode(',', $ConfVal));
110  $Options = explode("|", $row['option_value']);
111  $OutBuf .= "<div id='" . $row['variablename'] . "Div' style='display:inline-block; padding:5px;'>";
112  foreach ($Options as $Option) {
113  $matches = array();
114  preg_match('/([ \\w]+)\\{(.*)\\}/', $Option, $matches);
115  $Option_display = $matches[1];
116  $Option_value = $matches[2];
117  $isChecked = in_array($Option_value, $selectedIds) ? "checked" : "";
118  $OutBuf .= "<label style='margin-right:15px;'>";
119  $OutBuf .= "<input type='checkbox' name='new[" . $row['variablename'] . "][]' " .
120  "value='$Option_value' $isChecked /> $Option_display";
121  $OutBuf .= "</label>";
122  }
123  $OutBuf .= "</div>";
124  $OutBuf .= "<br>$row[description]";
125  break;
126  default:
127  $OutBuf .= "Invalid configuration variable. Unknown type.";
128  }
129  $OutBuf .= "</td></tr>";
130  $OutBuf .= "<INPUT type='hidden' name='old[$row[variablename]]' value='$ConfVal'>";
131  }
132  $OutBuf .= "</table>";
133  pg_free_result($result);
134 
135  $btnlabel = _("Update");
136  $OutBuf .= "<p><input type='submit' value='$btnlabel'>";
137  $OutBuf .= "</form>";
138 
139  $OutBuf .= "<script>
140  (function () {
141  var autoDetect = document.getElementById('ReuserAutoDetect');
142  var statusDiv = document.getElementById('ReuserSearchStatusDiv');
143  if (!autoDetect || !statusDiv) {
144  return;
145  }
146  var toggle = function () {
147  var greyed = !autoDetect.checked;
148  statusDiv.style.opacity = greyed ? '0.4' : '1';
149  statusDiv.style.pointerEvents = greyed ? 'none' : 'auto';
150  };
151  autoDetect.addEventListener('change', toggle);
152  toggle();
153  })();
154  </script>";
155 
156  return $OutBuf;
157  }
158 
162  function Output()
163  {
164  if ($this->State != PLUGIN_STATE_READY) {
165  return;
166  }
167 
168  $newarray = GetParm("new", PARM_RAW);
169  $oldarray = GetParm("old", PARM_RAW);
170 
171  if (!empty($newarray)) {
172  // Get missing keys from new array (unchecked checkboxes are not sent)
173  $boolFalseArray = array_diff_key($oldarray, $newarray);
174  foreach ($boolFalseArray as $varname => $value) {
175  // Make sure it was boolean or checklist data
176  $isBoolean = $this->dbManager->getSingleRow("SELECT 1 FROM sysconfig " .
177  "WHERE variablename = $1 AND vartype = " . CONFIG_TYPE_BOOL,
178  array($varname), __METHOD__ . '.checkIfBool');
179  if (! empty($isBoolean)) {
180  $newarray[$varname] = 'false';
181  continue;
182  }
183  $isChecklist = $this->dbManager->getSingleRow("SELECT 1 FROM sysconfig " .
184  "WHERE variablename = $1 AND vartype = " . CONFIG_TYPE_CHECKLIST,
185  array($varname), __METHOD__ . '.checkIfChecklist');
186  if (! empty($isChecklist)) {
187  $newarray[$varname] = '';
188  }
189  }
190  // Normalize checklist arrays to comma-separated strings
191  foreach ($newarray as $varname => $value) {
192  if (is_array($value)) {
193  $newarray[$varname] = implode(',', $value);
194  }
195  }
196  }
197 
198  /* Compare new and old array
199  * and update DB with new values */
200  $UpdateMsg = "";
201  $ErrorMsg="";
202  if (! empty($newarray)) {
203  // Fetch endpoints from OIDC documentation
204  if (! empty($newarray["OidcDiscoveryURL"]) &&
205  $newarray["OidcDiscoveryURL"] != $oldarray["OidcDiscoveryURL"]) {
206  $this->updateOidcEndpoints($newarray, $oldarray);
207  }
208  foreach ($newarray as $VarName => $VarValue) {
209  if ($VarValue != $oldarray[$VarName]) {
210  /* get validation_function row from sysconfig table */
211  $sys_array = $this->dbManager->getSingleRow("select validation_function, ui_label from sysconfig where variablename=$1",array($VarName),__METHOD__.'.getVarNameData');
212  $validation_function = $sys_array['validation_function'];
213  $ui_label = $sys_array['ui_label'];
214  $is_empty = empty($validation_function);
215  /* 1. the validation_function is empty
216  2. the validation_function is not empty, and after checking, the value is valid
217  update sysconfig table
218  */
219  if ($is_empty || (! $is_empty && (1 == $validation_function($VarValue)))) {
220  $this->dbManager->getSingleRow(
221  "update sysconfig set conf_value=$1 where variablename=$2",
222  array($VarValue, $VarName), __METHOD__ . '.setVarNameData');
223  if (! empty($UpdateMsg)) {
224  $UpdateMsg .= ", ";
225  }
226  $UpdateMsg .= $VarName;
227  } else if (! $is_empty && (0 == $validation_function($VarValue))) {
228  /*
229  * the validation_function is not empty, but after checking, the value
230  * is invalid
231  */
232  if (! strcmp($validation_function, 'check_boolean')) {
233  $warning_msg = _(
234  "Error: You set $ui_label to ".htmlspecialchars($VarValue).". Valid values are 'true' and 'false'.");
235  echo "<script>alert('$warning_msg');</script>";
236  } else if (strpos($validation_function, "url")) {
237  $warning_msg = _(
238  "Error: $ui_label ".htmlspecialchars($VarValue).", is not a reachable URL.");
239  echo "<script>alert('$warning_msg');</script>";
240  }
241 
242  if (! empty($ErrorMsg)) {
243  $ErrorMsg .= ", ";
244  }
245  $ErrorMsg .= $VarName;
246 
247  }
248  }
249  }
250  if (! empty($UpdateMsg)) {
251  $UpdateMsg .= _(" updated.");
252  }
253  if (! empty($ErrorMsg)) {
254  $ErrorMsg .= _(" Error occurred.");
255  }
256  }
257 
258  $OutBuf = '';
259  if ($this->OutputType == 'HTML') {
260  $OutBuf .= "<div>";
261  if ($UpdateMsg) {
262  $OutBuf .= "<span style='background-color:#99FF99'>$UpdateMsg</style>";
263  }
264  if ($ErrorMsg) {
265  $OutBuf .= "<span style='background-color:#FF8181'>$ErrorMsg</style><hr>";
266  }
267  $OutBuf .= "</div> <hr>";
268  $OutBuf .= $this->HTMLout();
269  }
270  $this->vars['content'] = $OutBuf;
271  }
272 
283  private function updateOidcEndpoints(&$newarray, &$oldarray)
284  {
285  global $SysConf;
286  $client = new Client();
287  $proxy = [];
288  if (array_key_exists('http_proxy', $SysConf['FOSSOLOGY']) &&
289  ! empty($SysConf['FOSSOLOGY']['http_proxy'])) {
290  $proxy['http'] = $SysConf['FOSSOLOGY']['http_proxy'];
291  }
292  if (array_key_exists('https_proxy', $SysConf['FOSSOLOGY']) &&
293  ! empty($SysConf['FOSSOLOGY']['https_proxy'])) {
294  $proxy['https'] = $SysConf['FOSSOLOGY']['https_proxy'];
295  }
296  if (array_key_exists('no_proxy', $SysConf['FOSSOLOGY']) &&
297  ! empty($SysConf['FOSSOLOGY']['no_proxy'])) {
298  $proxy['no'] = explode(',', $SysConf['FOSSOLOGY']['no_proxy']);
299  }
300  try {
301  $res = $client->request("GET", $newarray["OidcDiscoveryURL"], [
302  "proxy" => $proxy
303  ]);
304  } catch (RequestException $e) {
305  return;
306  }
307  if ($res->getStatusCode() !== 200) {
308  return;
309  }
310  $body = (string)$res->getBody();
311  $body = json_decode($body, true);
312  // Reset old values to make sure the update happens
313  $oldarray["OidcIssuer"] = "";
314  $oldarray["OidcAuthorizeURL"] = "";
315  $oldarray["OidcAccessTokenURL"] = "";
316  $oldarray["OidcResourceURL"] = "";
317  $oldarray["OidcJwksURL"] = "";
318  $newarray["OidcIssuer"] = $body["issuer"];
319  $newarray["OidcAuthorizeURL"] = $body["authorization_endpoint"];
320  $newarray["OidcAccessTokenURL"] = $body["token_endpoint"];
321  $newarray["OidcResourceURL"] = $body["userinfo_endpoint"];
322  $newarray["OidcJwksURL"] = $body["jwks_uri"];
323  }
324 }
325 
326 $NewPlugin = new foconfig;
327 $NewPlugin->Initialize();
This is the Plugin class. All plugins should:
Definition: FO_Plugin.php:57
Definition: state.hpp:16
display and set FOSSology configuration
Output()
Generate output.
updateOidcEndpoints(&$newarray, &$oldarray)
Update OIDC endpoints from OIDC discovery document.
HTMLout()
Generate HTML output.
__construct()
base constructor. Most plugins will just use this
DBCheckResult($result, $sql, $filenm, $lineno)
Check the postgres result for unexpected errors. If found, treat them as fatal.
Definition: common-db.php:189
const PARM_RAW
Definition: common-parm.php:22
GetParm($parameterName, $parameterType)
This function will retrieve the variables and check data types.
Definition: common-parm.php:46
const CONFIG_TYPE_TEXTAREA
const CONFIG_TYPE_TEXT
const CONFIG_TYPE_DROP
const CONFIG_TYPE_INT
const CONFIG_TYPE_BOOL
const CONFIG_TYPE_CHECKLIST
const CONFIG_TYPE_PASSWORD
if(!function_exists('resolve_config_value')) $Options
Definition: fo_dbcheck.php:51
#define PLUGIN_DB_ADMIN
Plugin requires admin level permission on DB.
Definition: libfossology.h:39
foreach($Options as $Option=> $OptVal) if(0==$reference_flag &&0==$nomos_flag) $PG_CONN
fo_dbManager * dbManager
fo_dbManager object
Definition: process.c:16