FOSSology  4.4.0
Open Source License Compliance by Open Source Software
fossdash-config.php
Go to the documentation of this file.
1 <?php
2 /*
3  SPDX-FileCopyrightText: © Darshan Kansagara <kansagara.darshan97@gmail.com>
4 
5  SPDX-License-Identifier: GPL-2.0-only
6  Author: Darshan Kansagara <kansagara.darshan97@gmail.com>
7 */
8 
30 function FossdashConfigInit($sysconfdir, &$SysConf)
31 {
32  global $PG_CONN;
33 
34  /*
35  * Connect to the database. If the connection fails,
36  * DBconnect() will print a failure message and exit.
37  */
38  $PG_CONN = DBconnect($sysconfdir);
39 
40  global $container;
41  $postgresDriver = new \Fossology\Lib\Db\Driver\Postgres($PG_CONN);
42  $container->get('db.manager')->setDriver($postgresDriver);
43 
44  /**************** read/create/populate the fossdashconfig table *********/
45  /* create if fossdashconfig table if it doesn't exist */
46  $newTable = Create_fossdashconfig();
47 
48  /* populate it with core variables */
50 
51  /* populate the global $SysConf array with variable/value pairs */
52  $sql = "SELECT variablename, conf_value FROM fossdashconfig;";
53  $result = pg_query($PG_CONN, $sql);
54  DBCheckResult($result, $sql, __FILE__, __LINE__);
55 
56  while ($row = pg_fetch_assoc($result)) {
57  $SysConf['FOSSDASHCONFIG'][$row['variablename']] = $row['conf_value'];
58  }
59  pg_free_result($result);
60 
61  return;
62 }
63 
64 
72 {
73  global $PG_CONN;
74 
75  /* If fossdashconfig exists, then we are done */
76  $sql = "SELECT typlen FROM pg_type WHERE typname='fossdashconfig' limit 1;";
77  $result = pg_query($PG_CONN, $sql);
78  DBCheckResult($result, $sql, __FILE__, __LINE__);
79  $numrows = pg_num_rows($result);
80  pg_free_result($result);
81  if ($numrows > 0) {
82  return 0;
83  }
84 
85  /* Create the fossdashconfig table */
86  $sql = "
87 CREATE TABLE fossdashconfig (
88  fossdashconfig_pk serial NOT NULL PRIMARY KEY,
89  variablename character varying(30) NOT NULL UNIQUE,
90  conf_value text,
91  ui_label character varying(60) NOT NULL,
92  vartype int NOT NULL,
93  group_name character varying(20) NOT NULL,
94  group_order int,
95  description text NOT NULL,
96  validation_function character varying(40) DEFAULT NULL,
97  option_value character varying(40) DEFAULT NULL
98 );
99 ";
100 
101  $result = pg_query($PG_CONN, $sql);
102  DBCheckResult($result, $sql, __FILE__, __LINE__);
103  pg_free_result($result);
104 
105  /* Document columns */
106  $sql = "
107 COMMENT ON TABLE fossdashconfig IS 'System configuration values';
108 COMMENT ON COLUMN fossdashconfig.variablename IS 'Name of configuration variable';
109 COMMENT ON COLUMN fossdashconfig.conf_value IS 'value of config variable';
110 COMMENT ON COLUMN fossdashconfig.ui_label IS 'Label that appears on user interface to prompt for variable';
111 COMMENT ON COLUMN fossdashconfig.group_name IS 'Name of this variables group in the user interface';
112 COMMENT ON COLUMN fossdashconfig.group_order IS 'The order this variable appears in the user interface group';
113 COMMENT ON COLUMN fossdashconfig.description IS 'Description of variable to document how/where the variable value is used.';
114 COMMENT ON COLUMN fossdashconfig.validation_function IS 'Name of function to validate input. Not currently implemented.';
115 COMMENT ON COLUMN fossdashconfig.vartype IS 'variable type. 1=int, 2=text, 3=textarea, 4=password, 5=dropdown';
116 COMMENT ON COLUMN fossdashconfig.option_value IS 'If vartype is 5, provide options in format op1{val1}|op2{val2}|...';
117  ";
118  /* this is a non critical update */
119  $result = pg_query($PG_CONN, $sql);
120  DBCheckResult($result, $sql, __FILE__, __LINE__);
121  pg_free_result($result);
122  return 1;
123 }
124 
125 
130 {
131  global $PG_CONN;
132 
133  $columns = array("variablename", "conf_value", "ui_label", "vartype", "group_name",
134  "group_order", "description", "validation_function", "option_value");
135  $valueArray = array();
136 
137  $variable = "FossdashEnableDisable";
138  $FossdashEnableDisablePrompt = _('Enable/Disable Fossdash');
139  $FossdashEnableDisableDesc = _('Start(Enable) or stop(Disable) the Fossdash');
140  $valueArray[$variable] = array("'$variable'", "'0'", "'$FossdashEnableDisablePrompt'",
141  strval(CONFIG_TYPE_DROP), "'FossDashAPI'", "1", "'$FossdashEnableDisableDesc'", "null", "'Disable{0}|Enable{1}'");
142 
143  $variable = "FossDashReportingAPIUrl";
144  $fossdashApiUrlPrompt = _('FossDash Endpoint URL');
145  $URLValid = "check_fossdash_url";
146  $fossdashApiUrlDesc = _('Set the FossDash service endpoint. Disabled if empty.
147  <br>e.g. for Source Code : <i>"http://localhost:8086/write?db=fossology_db"</i> OR for Docker Setup : <i>"http://influxdb:8086/write?db=fossology_db"</i>.');
148  $valueArray[$variable] = array("'$variable'", "null", "'$fossdashApiUrlPrompt'",
149  strval(CONFIG_TYPE_TEXT), "'FossDashAPI'", "2", "'$fossdashApiUrlDesc'", "'$URLValid'", "null");
150 
151  $variable = "FossdashMetricConfig";
152  $FossdashMetricConfigPrompt = _('Fossdash metric-reporting config');
153  $FossdashMetricConfigValid = "check_fossdash_config";
154  $FossdashMetricConfigDesc = _('Modify the fossdash reporting metrics config. Leave empty to use default one.
155  <br>e.g. Reporting config file <a target="_blank" href="https://github.com/darshank15/GSoC_2020_FOSSOlogy/wiki/Configuration-for-Fossdash-metric-reporting">Here</a>.
156  <br>To add new query_metric : 1.Add query_metric name in <b>QUERIES_NAME</b> list. 2.Add same query_metric name and its corresponding DB_query under the <b>QUERY</b>');
157  $valueArray[$variable] = array("'$variable'", "null", "'$FossdashMetricConfigPrompt'",
158  strval(CONFIG_TYPE_TEXTAREA), "'FossDashAPI'", "3", "'$FossdashMetricConfigDesc'", "'$FossdashMetricConfigValid'", "null");
159 
160  $variable = "FossDashScriptCronSchedule";
161  $FossDashScriptCronSchedulePromt = _('cron job to run script');
162  $cronIntervalCheck= "check_cron_job_inteval";
163  $FossDashScriptCronScheduleDesc = _('Set the cron job of publishing script file for pushing data to time series db.');
164  $valueArray[$variable] = array("'$variable'", "'* * * * *'", "'$FossDashScriptCronSchedulePromt'",
165  strval(CONFIG_TYPE_TEXT), "'FossDashAPI'", "4", "'$FossDashScriptCronScheduleDesc'", "'$cronIntervalCheck'", "null");
166 
167  $variable = "FossologyInstanceName";
168  $FossologyInstanceNamePrompt = _('Fosslogy instance name');
169  $instanceNameValid = "check_fossology_instance_name";
170  $FossologyInstanceNameDesc = _('Set the fossology instance name, leave empty to use autogenerated UUID value.
171  <br>e.g. Instance name formate = <b>[a-zA-Z0-9_-]+ </b>.');
172  $valueArray[$variable] = array("'$variable'", "null", "'$FossologyInstanceNamePrompt'",
173  strval(CONFIG_TYPE_TEXT), "'FossDashAPI'", "5", "'$FossologyInstanceNameDesc'", "'$instanceNameValid'", "null");
174 
175  $variable = "FossdashReportedCleaning";
176  $FossdashReportingCleaningPrompt = _('Fossdash reported files cleaning');
177  $FossdashReportingCleaningValid = "check_fossdash_cleaning";
178  $FossdashReportingCleaningDesc = _('number of days for which the successfully pushed metrics are archived. Older data will be deleted. Leave empty to disable cleanup');
179  $valueArray[$variable] = array("'$variable'", "null", "'$FossdashReportingCleaningPrompt'",
180  strval(CONFIG_TYPE_TEXT), "'FossDashAPI'", "6", "'$FossdashReportingCleaningDesc'", "'$FossdashReportingCleaningValid'", "null");
181 
182  $variable = "AuthType";
183  $AuthTypePrompt = _('Auth_type for InfluxDB');
184  $AuthTypeDesc = _('Select authentication type for an InfluxDB');
185  $valueArray[$variable] = array("'$variable'", "'0'", "'$AuthTypePrompt'",
186  strval(CONFIG_TYPE_DROP), "'FossDashAPI'", "7", "'$AuthTypeDesc'", "null", "'Token_based{0}|Uname_pass{1}'");
187 
188  $variable = "InfluxDBUser";
189  $InfluxDBUserPrompt = _('InlfuxDB User');
190  $InfluxDBUserValid = "check_username";
191  $InfluxDBUserDesc = _('Set the username for InfluxDB.');
192  $valueArray[$variable] = array("'$variable'", "null", "'$InfluxDBUserPrompt'",
193  strval(CONFIG_TYPE_TEXT), "'FossDashAPI'", "8", "'$InfluxDBUserDesc'", "'$InfluxDBUserValid'", "null");
194 
195  $variable = "InfluxDBUserPassword";
196  $InfluxDBUserPasswordPrompt = _('InlfuxDB Password');
197  $InfluxDBUserPasswordValid = "check_password";
198  $InfluxDBUserPasswordDesc = _('Set the password for Influx user. Password must atleast of lenght=3');
199  $valueArray[$variable] = array("'$variable'", "null", "'$InfluxDBUserPasswordPrompt'",
200  strval(CONFIG_TYPE_PASSWORD), "'FossDashAPI'", "9", "'$InfluxDBUserPasswordDesc'", "'$InfluxDBUserPasswordValid'", "null");
201 
202  $variable = "InfluxDBToken";
203  $InfluxDBTokenPrompt = _('InlfuxDB Encoded Token');
204  $InfluxDBTokenDesc = _('Please Enter encoded token for InfluxDB Authentication.
205  <br>Check out the steps for <a target="_blank" href="https://github.com/darshank15/GSoC_2020_FOSSOlogy/wiki/Steps-to-generate-InfluxDB-token">Token Generation</a>.');
206  $valueArray[$variable] = array("'$variable'", "null", "'$InfluxDBTokenPrompt'",
207  strval(CONFIG_TYPE_TEXTAREA), "'FossDashAPI'", "10", "'$InfluxDBTokenDesc'", "null", "null");
208 
209  /* Doing all the rows as a single insert will fail if any row is a dupe.
210  So insert each one individually so that new variables get added.
211  */
212  foreach ($valueArray as $variable => $values) {
213  /*
214  * Check if the variable already exists. Insert it if it does not.
215  * This is better than an insert ignoring duplicates, because that
216  * generates a postresql log message.
217  */
218  $VarRec = GetSingleRec("fossdashconfig", "WHERE variablename='$variable'");
219  if (empty($VarRec)) {
220  $sql = "INSERT INTO fossdashconfig (" . implode(",", $columns) . ") VALUES (" .
221  implode(",", $values) . ");";
222  } else { // Values exist, update them
223  $updateString = [];
224  foreach ($columns as $index => $column) {
225  if ($index != 0 && $index != 1) { // Skip variablename and conf_value
226  $updateString[] = $column . "=" . $values[$index];
227  }
228  }
229  $sql = "UPDATE fossdashconfig SET " . implode(",", $updateString) .
230  " WHERE variablename='$variable';";
231  }
232  $result = pg_query($PG_CONN, $sql);
233  DBCheckResult($result, $sql, __FILE__, __LINE__);
234  pg_free_result($result);
235  unset($VarRec);
236  }
237 
238 }
239 
240 
246 function check_fossdash_url($url)
247 {
248  if (filter_var($url, FILTER_VALIDATE_URL) && preg_match("#^((http)|(https)|(ftp)|(www)|(localhost))://(.*)#", $url) == 1) {
249  return 1;
250  } else {
251  return 0;
252  }
253 }
254 
260 function check_cron_job_inteval($cron_interval)
261 {
262  $cron_regex = "#^((@(annually|yearly|monthly|weekly|daily|hourly|reboot))|(@every (\d+(ns|us|µs|ms|s|m|h))+)|((((\d+,)+\d+|(\d+(\/|-)\d+)|\d+|\*|\*\/\d+) ?){5}))$#";
263  return preg_match($cron_regex, $cron_interval);
264 }
265 
266 
272 function check_fossology_instance_name($instance_name)
273 {
274  $instance_UUID_regex = "#^([a-zA-Z0-9_-]+)$#";
275  return preg_match($instance_UUID_regex, $instance_name);
276 }
277 
283 function check_fossdash_cleaning($cleaning_days)
284 {
285  $numeric_day_regex = "#^[0-9]*$#";
286  return preg_match($numeric_day_regex, $cleaning_days);
287 }
288 
294 function check_username($uname)
295 {
296  $uname_regex = "#^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$#";
297  return preg_match($uname_regex, $uname);
298 }
299 
305 function check_password($password)
306 {
307  $password_regex = "#^(?=.*[A-Za-z])[A-Za-z\d]{3,}$#";
308  return preg_match($password_regex, $password);
309 }
310 
316 function check_fossdash_config($config_str)
317 {
318  $lower_config_str = strtolower($config_str);
319  $db_update_command_list = array("drop", "insert", "update", "alter", "truncate", "delete");
320  foreach ($db_update_command_list as $cmd) {
321  if (strpos($lower_config_str,$cmd) !== false) {
322  return 0;
323  }
324  }
325  return 1;
326 }
DBconnect($sysconfdir, $options="", $exitOnFail=true)
Connect to database engine. This is a no-op if $PG_CONN already has a value.
Definition: common-db.php:33
DBCheckResult($result, $sql, $filenm, $lineno)
Check the postgres result for unexpected errors. If found, treat them as fatal.
Definition: common-db.php:187
GetSingleRec($Table, $Where="")
Retrieve a single database record.
Definition: common-db.php:91
const CONFIG_TYPE_TEXTAREA
const CONFIG_TYPE_TEXT
const CONFIG_TYPE_DROP
const CONFIG_TYPE_PASSWORD
check_password($password)
Check if given password is valid or not.
check_fossdash_url($url)
Check if the fossdash url is valid.
check_fossology_instance_name($instance_name)
Check if the fossology instance name is valid.
Populate_fossdashconfig()
Populate the fossdashconfig table with core variables.
Create_fossdashconfig()
Create the fossdashconfig table.
check_username($uname)
Check if given uname is valid or not.
check_cron_job_inteval($cron_interval)
Check if the cron job schedule interval is valid.
check_fossdash_config($config_str)
Check if given config string does not contains any DB update or drop related commands.
FossdashConfigInit($sysconfdir, &$SysConf)
Initialize the fossdash configuration after bootstrap().
check_fossdash_cleaning($cleaning_days)
Check if cleaning_days is valid or not.
foreach($Options as $Option=> $OptVal) if(0==$reference_flag &&0==$nomos_flag) $PG_CONN