FOSSology  4.4.0
Open Source License Compliance by Open Source Software
ui-spasht.php
1 <?php
2 /*
3  SPDX-FileCopyrightText: © 2019 Vivek Kumar <vvksindia@gmail.com>
4  Author: Vivek Kumar<vvksindia@gmail.com>
5 
6  SPDX-License-Identifier: GPL-2.0-only
7 */
8 
16 use GuzzleHttp\Client;
17 use GuzzleHttp\Exception\RequestException;
18 use GuzzleHttp\Exception\ClientException;
19 use GuzzleHttp\Exception\ServerException;
20 
21 include_once(dirname(__DIR__) . "/agent/version.php");
22 
27 class ui_spasht extends FO_Plugin
28 {
29 
34  private $spashtDao;
35 
40  protected $viewName;
41 
46  protected $agentDao;
47 
48  function __construct()
49  {
50  $this->Name = "spashtbrowser";
51  $this->Title = _("Spasht Browser");
52  $this->Dependency = array("browse","view");
53  $this->DBaccess = PLUGIN_DB_WRITE;
54  $this->LoginFlag = 0;
55  $this->uploadDao = $GLOBALS['container']->get('dao.upload');
56  $this->spashtDao = $GLOBALS['container']->get('dao.spasht');
57  $this->agentDao = $GLOBALS['container']->get('dao.agent');
58  $this->viewName = "view";
59  $this->renderer = $GLOBALS['container']->get('twig.environment');
60  $this->agentName = "spasht";
61  $this->vars['name'] = $this->Name;
62 
63  parent::__construct();
64  }
65 
69  function RegisterMenus()
70  {
71  // For all other menus, permit coming back here.
72  $URI = $this->Name . Traceback_parm_keep(array(
73  "show", "format", "page", "upload", "item"));
74  $Item = GetParm("item", PARM_INTEGER);
75  $Upload = GetParm("upload", PARM_INTEGER);
76  if (! empty($Item) && ! empty($Upload)) {
77  $menuText = "Spasht";
78  $tooltipText = _("View in clearlydefined");
79  $menuPosition = 55;
80  if (GetParm("mod", PARM_STRING) == $this->Name) {
81  menu_insert("Browse::$menuText", $menuPosition);
82  menu_insert("Browse::[BREAK]", 100);
83  } else {
84  menu_insert("Browse::$menuText", $menuPosition, $URI, $tooltipText);
85  menu_insert("View::$menuText", $menuPosition, $URI, $tooltipText);
86  }
87  }
88  } // RegisterMenus()
89 
100  function Initialize()
101  {
102  global $_GET;
103 
104  if ($this->State != PLUGIN_STATE_INVALID) {
105  return(1);
106  } // don't re-run
107  if ($this->Name !== "") {
108  global $Plugins;
109  $this->State=PLUGIN_STATE_VALID;
110  $Plugins[] = $this;
111  }
112  return($this->State == PLUGIN_STATE_VALID);
113  } // Initialize()
114 
119  public function Output()
120  {
121  global $SysConf;
122 
123  $statusbody = "definition_not_found";
124 
125  $optionSelect = trim(GetParm("optionSelectedToOpen", PARM_STRING));
126  $patternName = trim(GetParm("patternName", PARM_STRING)); // Get the entry
127  // from search box
128  $revisionName = trim(GetParm("revisionName", PARM_STRING));
129  $namespaceName = trim(GetParm("namespaceName", PARM_STRING));
130  $typeName = trim(GetParm("typeName", PARM_STRING));
131  $providerName = trim(GetParm("providerName", PARM_STRING));
132 
133  $this->vars['storeStatus'] = "false";
134  $this->vars['pageNo'] = "definition_not_found";
135 
136  $uploadId = GetParm("upload", PARM_INTEGER);
137 
138  /* check upload permissions */
139  if (empty($uploadId)) {
140  return 'no item selected';
141  } elseif (!$this->uploadDao->isAccessible($uploadId, Auth::getGroupId())) {
142  $text = _("Permission Denied");
143  return "<h2>$text</h2>";
144  }
145 
146  $upload_name = preg_replace(
147  '/(?i)(?:\.(?:tar\.xz|tar\.bz2|tar\.gz|zip|tgz|tbz|txz|tar))/', "",
148  GetUploadName($uploadId));
149  $uri = preg_replace("/&item=([0-9]*)/", "", Traceback());
150  $uploadtree_pk = GetParm("item",PARM_INTEGER);
151  $uploadtree_tablename = GetUploadtreeTableName($uploadId);
152  $agentId = $this->agentDao->getCurrentAgentId("spasht");
153 
154  $this->vars['micromenu'] = Dir2Browse($this->Name, $uploadtree_pk, null,
155  false, "Browse", -1, '', '', $uploadtree_tablename);
156 
157  if (!empty($optionSelect)) {
158  $patternName = $this->handleNewSelection($optionSelect, $uploadId);
159  }
160 
161  if ($patternName != null && !empty($patternName)) {//Check if search is not empty
163  $client = new Client([
164  // Base URI is used with relative requests
165  'base_uri' => $SysConf['SYSCONFIG']["ClearlyDefinedURL"]
166  ]);
167  // Prepare proxy
168  $proxy = [];
169  if (array_key_exists('http_proxy', $SysConf['FOSSOLOGY']) &&
170  ! empty($SysConf['FOSSOLOGY']['http_proxy'])) {
171  $proxy['http'] = $SysConf['FOSSOLOGY']['http_proxy'];
172  }
173  if (array_key_exists('https_proxy', $SysConf['FOSSOLOGY']) &&
174  ! empty($SysConf['FOSSOLOGY']['https_proxy'])) {
175  $proxy['https'] = $SysConf['FOSSOLOGY']['https_proxy'];
176  }
177  if (array_key_exists('no_proxy', $SysConf['FOSSOLOGY']) &&
178  ! empty($SysConf['FOSSOLOGY']['no_proxy'])) {
179  $proxy['no'] = explode(',', $SysConf['FOSSOLOGY']['no_proxy']);
180  }
181 
182  try {
183  // Point to definitions section in the api
184  $res = $client->request('GET', 'definitions', [
185  'query' => ['pattern' => $patternName], //Perform query operation into the api
186  'proxy' => $proxy
187  ]);
188  } catch (RequestException $e) {
189  $this->vars['message'] = "Unable to reach " .
190  $SysConf['SYSCONFIG']["ClearlyDefinedURL"] . ". Code: " .
191  $e->getCode();
192  return $this->render('agent_spasht.html.twig', $this->vars);
193  } catch (ClientException $e) {
194  $this->vars['message'] = "Request failed. Status: " .
195  $e->getCode();
196  return $this->render('agent_spasht.html.twig', $this->vars);
197  } catch (ServerException $e) {
198  $this->vars['message'] = "Request failed. Status: " .
199  $e->getCode();
200  return $this->render('agent_spasht.html.twig', $this->vars);
201  }
202 
203  if ($res->getStatusCode()==200) {//Get the status of http request
204  $findings = json_decode($res->getBody()->getContents());
205 
206  if (count($findings) == 0) {//Check if no element is found
207  $statusbody = "definition_not_found";
208  } else {
209  $matches = array();
210  $details = array();
211 
212  foreach ($findings as $finding) {
213  $obj = Coordinate::generateFromString($finding);
214 
215  if ($this->checkAdvanceSearch($obj, $revisionName, $namespaceName,
216  $typeName, $providerName)) {
217  $uri = "definitions/" . $obj->generateUrlString();
218 
219  //details section
220  try {
221  $res_details = $client->request('GET', $uri, [
222  'query' => [
223  'expand' => "-files"
224  ], //Perform query operation into the api
225  'proxy' => $proxy
226  ]);
227  } catch (RequestException $e) {
228  $this->vars['message'] = "Unable to reach " .
229  $SysConf['SYSCONFIG']["ClearlyDefinedURL"] . ". Code: " .
230  $e->getCode();
231  return $this->render('agent_spasht.html.twig', $this->vars);
232  } catch (ClientException $e) {
233  $this->vars['message'] = "Request failed. Status: " .
234  $e->getCode();
235  return $this->render('agent_spasht.html.twig', $this->vars);
236  } catch (ServerException $e) {
237  $this->vars['message'] = "Request failed. Status: " .
238  $e->getCode();
239  return $this->render('agent_spasht.html.twig', $this->vars);
240  }
241 
242  $detail_body = json_decode($res_details->getBody()->getContents(),
243  true);
244 
245  $details_temp = new DefinitionSummary($detail_body);
246  $obj->setScore($details_temp->getScore());
247 
248  $matches[] = $obj;
249  $details[] = $details_temp;
250  }
251  }
252  if (!empty($details)) {
253  $this->vars['details'] = $details;
254  $this->vars['body'] = $matches;
255  $statusbody = "definition_found";
256  } else {
257  $statusbody = "definition_not_found";
258  }
259  }
260  }
261 
262  if ($statusbody == "definition_found") {
263  $this->vars['pageNo'] = "show_definitions";
264  } else {
265  $this->vars['pageNo'] = "definition_not_found";
266  }
267  $upload_name = $patternName;
268  } else {
269  $this->vars['pageNo'] = "Please Search and Select Revision";
270 
271  $searchUploadId = $this->spashtDao->getComponent($uploadId);
272 
273  if (! empty($searchUploadId)) {
274  $this->vars['pageNo'] = "show_upload_table";
275  $this->vars['body'] = $searchUploadId;
276 
277  $message = "";
278 
279  $plugin = plugin_find($this->agentName);
280  if ($plugin == null) {
281  $message = "Agent spasht not installed";
282  } else {
283  $results = $plugin->AgentHasResults($uploadId);
284  $running = isAlreadyRunning($this->agentName, $uploadId);
285  if ($results != 0 && $running == 0) {
286  $message = "Scan completed successfully\n";
287  } else {
288  $jobUrl = Traceback_uri() . "?mod=showjobs&upload=$uploadId";
289  $message = _("Agent scheduled.") . " <a href=$jobUrl>Show</a>\n";
290  }
291  }
292  $this->vars['body_menu'] = $message;
293  }
294  }
295  $table = array();
296 
297  $table['uploadId'] = $uploadId;
298  $table['uploadTreeId'] = $uploadtree_pk;
299  $table['agentId'] = $agentId;
300  $table['type'] = 'statement';
301  $table['filter'] = 'Show all';
302  $table['sorting'] = json_encode($this->returnSortOrder());
303  $this->vars['tables'] = [$table];
304 
305  $advanceSearchFormStatus = "hidden";
306  if (empty(trim(GetParm("advanceSearchFormStatus", PARM_STRING)))) {
307  // First load
312  $coord = $this->spashtDao->getCoordinateFromCompId($uploadId);
313  if ($coord != null) {
314  $upload_name = $coord->getName();
315  $revisionName = $coord->getRevision();
316  $namespaceName = $coord->getNamespace();
317  $typeName = $coord->getType();
318  $providerName = $coord->getProvider();
319  $advanceSearchFormStatus = "show";
320  }
321  }
322  $this->vars['uploadName'] = $upload_name;
323  $this->vars['revisionName'] = $revisionName;
324  $this->vars['namespaceName'] = $namespaceName;
325  $this->vars['typeName'] = $typeName;
326  $this->vars['providerName'] = $providerName;
327  if (! empty($revisionName) || ! empty($namespaceName) || ! empty($typeName)
328  || ! empty($providerName)) {
329  $advanceSearchFormStatus = "show";
330  }
331 
332  $this->vars['advanceSearchFormStatus'] = $advanceSearchFormStatus;
333  $this->vars['fileList'] = $this->getFileListing($uploadtree_pk, $uri,
334  $uploadtree_tablename, $agentId, $uploadId);
335 
336  $out = $this->render('agent_spasht.html.twig', $this->vars);
337 
338  return($out);
339  }
340 
349  protected function getFileListing($Uploadtree_pk, $Uri, $uploadtree_tablename,
350  $Agent_pk, $upload_pk)
351  {
352  /******* File Listing ************/
353  /* Get ALL the items under this Uploadtree_pk */
354  $Children = GetNonArtifactChildren($Uploadtree_pk, $uploadtree_tablename);
355 
356  $tableData = [];
357  $uploadInfo = $this->uploadDao->getUploadEntry($Uploadtree_pk,
358  $uploadtree_tablename);
359  if (! empty($uploadInfo['parent'])) {
360  $uploadtree_pk = $uploadInfo['parent'];
361  $row = [];
362  $row['url'] = "$Uri&item=$uploadtree_pk";
363  $row['content'] = "../";
364  $row['id'] = $uploadInfo['uploadtree_pk'];
365  $tableData[] = $row;
366  }
367 
368  foreach ($Children as $child) {
369  if (empty($child)) {
370  continue;
371  }
372 
373  /* Populate the output ($VF) - file list */
374  /* id of each element is its uploadtree_pk */
375  $cellContent = Isdir($child['ufile_mode']) ? $child['ufile_name'].'/' : $child['ufile_name'];
376 
377  if (Iscontainer($child['ufile_mode'])) {
378  $uploadtree_pk = DirGetNonArtifact($child['uploadtree_pk'], $uploadtree_tablename);
379  $LinkUri = "$Uri&item=" . $uploadtree_pk;
380  } else {
381  $LinkUri = Traceback_uri();
382  $LinkUri .= "?mod=".$this->viewName."&agent=$Agent_pk&upload=$upload_pk&item=$child[uploadtree_pk]";
383  }
384 
385  $row = [];
386  $row['url'] = $LinkUri;
387  $row['content'] = $cellContent;
388  $row['id'] = $child['uploadtree_pk'];
389  $tableData[] = $row;
390  }
391  return $tableData;
392  }
393 
399  protected function isADirectory($Uploadtree_pk)
400  {
401  $row = $this->uploadDao->getUploadEntry($Uploadtree_pk, $this->uploadtree_tablename);
402  return IsDir($row['ufile_mode']);
403  }
404 
409  public function returnSortOrder ()
410  {
411  return array (
412  array(0, "desc"),
413  array(1, "desc"),
414  );
415  }
416 
426  public function checkAdvanceSearch($coord, $revisionName, $namespaceName,
427  $typeName, $providerName)
428  {
429  if (! empty($revisionName) && $coord->getRevision() != $revisionName) {
430  return false;
431  }
432 
433  if (! empty($namespaceName) && $coord->getNamespace() != $namespaceName) {
434  return false;
435  }
436 
437  if (! empty($typeName) && $coord->getType() != $typeName) {
438  return false;
439  }
440 
441  if (! empty($providerName) && $coord->getProvider() != $providerName) {
442  return false;
443  }
444 
445  return true;
446  }
447 
453  private function handleNewSelection($optionSelect, $uploadId)
454  {
455  $patternName = null;
456  $selection = Coordinate::generateFromString($optionSelect);
457 
458  $uploadAvailable = $this->spashtDao->getComponent($uploadId);
459  if (! empty($uploadAvailable)) {
460  $result = $this->spashtDao->alterComponentRevision($selection, $uploadId);
461  } else {
462  $result = $this->spashtDao->addComponentRevision($selection, $uploadId);
463  }
464 
465  if ($result >= 0) {
466  $patternName = null;
467 
468  $userId = Auth::getUserId();
469  $groupId = Auth::getGroupId();
470  $errorMessage = "";
471 
472  $plugin = plugin_find($this->agentName);
473  $jobId = JobAddJob($userId, $groupId, $this->agentName, $uploadId);
474  $rv = $plugin->AgentAdd($jobId, $uploadId, $errorMessage);
475  if ($rv < 0) {
476  $text = _("Scheduling of agent failed: ");
477  $this->vars['message'] = $text . $errorMessage;
478  } elseif ($rv == 0) {
479  $text = _("Agent already scheduled");
480  $this->vars['message'] = $text;
481  } else {
482  $text = _("Agent scheduled successfully.");
483  $jobUrl = Traceback_uri() . "?mod=showjobs&upload=$uploadId";
484  $this->vars['message'] = "$text <a href=$jobUrl>Show</a>";
485  }
486  } else {
487  $patternName = $selection->getName();
488  }
489  return $patternName;
490  }
491 }
492 
493 $NewPlugin = new ui_spasht;
494 $NewPlugin->Initialize();
char * uploadtree_tablename
upload.uploadtree_tablename
Definition: adj2nest.c:100
This is the Plugin class. All plugins should:
Definition: FO_Plugin.php:57
Output()
This function is called when user output is requested. This function is responsible for content....
Definition: FO_Plugin.php:399
render($templateName, $vars=null)
Definition: FO_Plugin.php:434
Contains the constants and helpers for authentication of user.
Definition: Auth.php:24
Definition: state.hpp:16
RegisterMenus()
Customize submenus.
Definition: ui-spasht.php:69
handleNewSelection($optionSelect, $uploadId)
Definition: ui-spasht.php:453
Initialize()
This is called before the plugin is used. It should assume that Install() was already run one time (p...
Definition: ui-spasht.php:100
__construct()
base constructor. Most plugins will just use this
Definition: ui-spasht.php:48
returnSortOrder()
Get sorting orders.
Definition: ui-spasht.php:409
checkAdvanceSearch($coord, $revisionName, $namespaceName, $typeName, $providerName)
Check for Advance Search.
Definition: ui-spasht.php:426
getFileListing($Uploadtree_pk, $Uri, $uploadtree_tablename, $Agent_pk, $upload_pk)
Definition: ui-spasht.php:349
isADirectory($Uploadtree_pk)
Check if passed element is a directory.
Definition: ui-spasht.php:399
Isdir($mode)
Definition: common-dir.php:20
DirGetNonArtifact($UploadtreePk, $uploadtree_tablename='uploadtree')
Given an artifact directory (uploadtree_pk), return the first non-artifact directory (uploadtree_pk).
Definition: common-dir.php:158
Iscontainer($mode)
Definition: common-dir.php:38
Dir2Browse($Mod, $UploadtreePk, $LinkLast=NULL, $ShowBox=1, $ShowMicro=NULL, $Enumerate=-1, $PreText='', $PostText='', $uploadtree_tablename="uploadtree")
Get an html linked string of a file browse path.
Definition: common-dir.php:263
isAlreadyRunning($agentName, $upload_pk)
Check if an agent is already running in a job.
Definition: common-job.php:498
menu_insert($Path, $LastOrder=0, $URI=NULL, $Title=NULL, $Target=NULL, $HTML=NULL)
Given a Path, order level for the last item, and optional plugin name, insert the menu item.
Traceback_uri()
Get the URI without query to this location.
Definition: common-parm.php:97
const PARM_INTEGER
Definition: common-parm.php:14
Traceback()
Get the URI + query to this location.
Definition: common-parm.php:89
const PARM_STRING
Definition: common-parm.php:18
GetParm($parameterName, $parameterType)
This function will retrieve the variables and check data types.
Definition: common-parm.php:46
Traceback_parm_keep($List)
Create a new URI, keeping only these items.
plugin_find($pluginName)
Given the official name of a plugin, return the $Plugins object.
GetUploadName($upload_pk)
Get Upload Name through upload id.
Definition: common-ui.php:251
char * trim(char *ptext)
Trimming whitespace.
Definition: fossconfig.c:690
FUNCTION char * GetUploadtreeTableName(PGconn *pgConn, int upload_pk)
Get the uploadtree table name for this upload_pk If upload_pk does not exist, return "uploadtree".
Definition: libfossagent.c:414
#define PLUGIN_DB_WRITE
Plugin requires write permission on DB.
Definition: libfossology.h:38
int IsDir(char *Fname)
Given a filename, is it a directory?
Definition: utils.c:319