FOSSology  4.4.0
Open Source License Compliance by Open Source Software
UploadPageBase.php
1 <?php
2 /*
3  SPDX-FileCopyrightText: © 2015 Siemens AG
4 
5  SPDX-License-Identifier: GPL-2.0-only
6 */
7 
8 namespace Fossology\UI\Page;
9 
16 use Monolog\Logger;
17 use Symfony\Component\HttpFoundation\Request;
18 
19 abstract class UploadPageBase extends DefaultPlugin
20 {
21  const NAME = "upload_file";
22  const FOLDER_PARAMETER_NAME = 'folder';
23 
24  const DESCRIPTION_INPUT_NAME = 'descriptionInputName';
25  const DESCRIPTION_VALUE = 'descriptionValue';
26  const UPLOAD_FORM_BUILD_PARAMETER_NAME = 'uploadformbuild';
27  const PUBLIC_ALL = 'public';
28  const PUBLIC_GROUPS = 'protected';
29 
31  private $folderDao;
33  private $uploadDao;
35  private $logger;
37  private $userDao;
38 
39  public function __construct($name, $parameters = array())
40  {
41  parent::__construct($name, $parameters);
42 
43  $this->folderDao = $this->getObject('dao.folder');
44  $this->uploadDao = $this->getObject('dao.upload');
45  $this->logger = $this->getObject('logger');
46  $this->userDao = $this->getObject('dao.user');
47  }
48  abstract protected function handleUpload(Request $request);
49  abstract protected function handleView(Request $request, $vars);
50 
51  protected function handle(Request $request)
52  {
53  // Handle request
54  $this->folderDao->ensureTopLevelFolder();
55 
56  $message = "";
57  $description = "";
58  if ($request->isMethod(Request::METHOD_POST)) {
59  list($success, $message, $description) = $this->handleUpload($request);
60  }
61  $vars['message'] = $message;
62  $vars['descriptionInputValue'] = $description ?: "";
63  $vars['descriptionInputName'] = self::DESCRIPTION_INPUT_NAME;
64  $vars['folderParameterName'] = self::FOLDER_PARAMETER_NAME;
65  $vars['upload_max_filesize'] = ini_get('upload_max_filesize');
66  $vars['agentCheckBoxMake'] = '';
67  global $SysConf;
68  $userId = Auth::getUserId();
69  $UserRec = $this->userDao->getUserByPk($userId);
70  if (!empty($UserRec['upload_visibility'])) {
71  $vars['uploadVisibility'] = $UserRec['upload_visibility'];
72  } else {
73  $vars['uploadVisibility'] = $SysConf['SYSCONFIG']['UploadVisibility'];
74  }
75  $rootFolder = $this->folderDao->getDefaultFolder(Auth::getUserId());
76  if ($rootFolder == NULL) {
77  $rootFolder = $this->folderDao->getRootFolder(Auth::getUserId());
78  }
79  $folderStructure = $this->folderDao->getFolderStructure($rootFolder->getId());
80 
81  $vars['folderStructure'] = $folderStructure;
82  $vars['baseUrl'] = $request->getBaseUrl();
83  $vars['moduleName'] = $this->getName();
84  $vars[self::FOLDER_PARAMETER_NAME] = $request->get(self::FOLDER_PARAMETER_NAME);
85 
86  $parmAgentList = MenuHook::getAgentPluginNames("ParmAgents");
87  $vars['parmAgentContents'] = array();
88  $vars['parmAgentFoots'] = array();
89  foreach ($parmAgentList as $parmAgent) {
90  $agent = plugin_find($parmAgent);
91  $vars['parmAgentContents'][] = $agent->renderContent($vars);
92  $vars['parmAgentFoots'][] = $agent->renderFoot($vars);
93  }
94 
95  $session = $request->getSession();
96  $session->set(self::UPLOAD_FORM_BUILD_PARAMETER_NAME, time().':'.$_SERVER['REMOTE_ADDR']);
97  $vars['uploadFormBuild'] = $session->get(self::UPLOAD_FORM_BUILD_PARAMETER_NAME);
98  $vars['uploadFormBuildParameterName'] = self::UPLOAD_FORM_BUILD_PARAMETER_NAME;
99 
100  if (@$_SESSION[Auth::USER_LEVEL] >= PLUGIN_DB_WRITE) {
101  $skip = array("agent_unpack", "agent_adj2nest", "wget_agent");
102  $vars['agentCheckBoxMake'] = AgentCheckBoxMake(-1, $skip);
103  }
104  return $this->handleView($request, $vars);
105  }
106 
107  protected function postUploadAddJobs(Request $request, $fileName, $uploadId, $jobId = null, $wgetDependency = false)
108  {
109  $userId = Auth::getUserId();
110  $groupId = Auth::getGroupId();
111 
112  if ($jobId === null) {
113  $jobId = JobAddJob($userId, $groupId, $fileName, $uploadId);
114  }
115  $dummy = "";
116  $unpackArgs = intval($request->get('scm')) == 1 ? '-I' : '';
117  $adj2nestDependencies = array();
118  if ($wgetDependency) {
119  $adj2nestDependencies = array(array('name'=>'agent_unpack','args'=>$unpackArgs,AgentPlugin::PRE_JOB_QUEUE=>array('wget_agent')));
120  }
121  $adj2nestplugin = \plugin_find('agent_adj2nest');
122  $adj2nestplugin->AgentAdd($jobId, $uploadId, $dummy, $adj2nestDependencies,
123  null, null, (empty($adj2nestDependencies) ? $unpackArgs : ''));
124 
125  $checkedAgents = checkedAgents();
126  AgentSchedule($jobId, $uploadId, $checkedAgents);
127 
128  $errorMsg = '';
129  $parmAgentList = MenuHook::getAgentPluginNames("ParmAgents");
130  $plainAgentList = MenuHook::getAgentPluginNames("Agents");
131  $agentList = array_merge($plainAgentList, $parmAgentList);
132 
133  $this->rearrangeDependencies($parmAgentList);
134 
135  foreach ($parmAgentList as $parmAgent) {
136  $agent = plugin_find($parmAgent);
137  $agent->scheduleAgent($jobId, $uploadId, $errorMsg, $request, $agentList);
138  }
139 
140  $status = GetRunnableJobList();
141  $message = empty($status) ? _("Is the scheduler running? ") : "";
142  $jobUrl = Traceback_uri() . "?mod=showjobs&upload=$uploadId";
143  $message .= _("The file") . " " . $fileName . " " . _("has been uploaded. It is") .
144  ' <a href=' . $jobUrl . '>upload #' . $uploadId . "</a>.\n";
145  if ($request->get('public')==self::PUBLIC_GROUPS) {
146  $this->getObject('dao.upload.permission')->makeAccessibleToAllGroupsOf($uploadId, $userId);
147  }
148  return $message;
149  }
150 
160  function str_contains_notescaped_char($str, $char)
161  {
162  $pos = 0;
163  while ($pos < strlen($str) &&
164  ($pos = strpos($str,$char,$pos)) !== false) {
165  foreach (range(($pos++) -1, 1, -2) as $tpos) {
166  if ($tpos > 0 && $str[$tpos] !== '\\') {
167  break;
168  }
169  if ($tpos > 1 && $str[$tpos - 1] !== '\\') {
170  continue 2;
171  }
172  }
173  return true;
174  }
175  return false;
176  }
177 
185  function path_is_pattern($path)
186  {
187  return $this->str_contains_notescaped_char($path, '*')
188  || $this->str_contains_notescaped_char($path, '?')
189  || $this->str_contains_notescaped_char($path, '[')
190  || $this->str_contains_notescaped_char($path, '{');
191  }
192 
201  protected function path_can_escape($path)
202  {
203  return $this->str_contains_notescaped_char($path, '$')
204  || strpos($path,'..') !== false;
205  }
206 
217  function normalize_path($path, $host="localhost", $appendix="")
218  {
219  if (strpos($path,'/') === false || $path === '/') {
220  return false;
221  }
222  if ($this->path_is_pattern($path)) {
223  $bpath = basename($path);
224  if ($this->path_can_escape($bpath)) {
225  return false;
226  }
227 
228  if (strcmp($host,"localhost") === 0) {
229  return $this->normalize_path(dirname($path),
230  $host,
231  $bpath . ($appendix == '' ?
232  '' :
233  '/' . $appendix));
234  } else {
235  if ($this->path_can_escape($path)) {
236  return false;
237  }
238  return $path . ($appendix == '' ?
239  '' :
240  '/' . $appendix);
241  }
242  } else {
243  $rpath = realpath($path);
244  if ($rpath === false) {
245  return false;
246  }
247  return $rpath . ($appendix == '' ?
248  '' :
249  '/' . $appendix);
250  }
251  }
252 
253  function basicShEscaping($str)
254  {
255  $str = str_replace('\\', '\\\\', $str);
256  $str = str_replace('"', '\"', $str);
257  $str = str_replace('`', '\`', $str);
258  $str = str_replace('$', '\$', $str);
259  return $str;
260  }
261 
267  private function rearrangeDependencies(&$parmList)
268  {
269  $deciderKey = array_search('agent_decider', $parmList);
270  $reuserKey = array_search('agent_reuser', $parmList);
271  if ($deciderKey !== false && $reuserKey !== false) {
272  $temp = $parmList[$deciderKey];
273  $parmList[$deciderKey] = $parmList[$reuserKey];
274  $parmList[$reuserKey] = $temp;
275  }
276  }
277 }
Contains the constants and helpers for authentication of user.
Definition: Auth.php:24
static getUserId()
Get the current user's id.
Definition: Auth.php:68
static getGroupId()
Get the current user's group id.
Definition: Auth.php:80
static getAgentPluginNames($hook='Agents')
Definition: MenuHook.php:16
path_is_pattern($path)
checks, whether a path is a pattern from the perspective of a shell
path_can_escape($path)
checks, whether a path contains substrings, which could enable it to escape his prefix
str_contains_notescaped_char($str, $char)
checks, whether a string contains some special character without escaping
normalize_path($path, $host="localhost", $appendix="")
normalizes an path and returns FALSE on errors
AgentSchedule($jobId, $uploadId, $agents)
Schedule all given agents.
checkedAgents($agents=null)
read the UI form and return array of user selected agents Because input comes from the user,...
AgentCheckBoxMake($upload_pk, $SkipAgents=array(), $specified_username="")
Generate a checkbox list of available agents.
Traceback_uri()
Get the URI without query to this location.
Definition: common-parm.php:97
plugin_find($pluginName)
Given the official name of a plugin, return the $Plugins object.
GetRunnableJobList()
Get runnable job list, the process is below:
#define PLUGIN_DB_WRITE
Plugin requires write permission on DB.
Definition: libfossology.h:38
list_t type structure used to keep various lists. (e.g. there are multiple lists).
Definition: nomos.h:308