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, null, (empty($adj2nestDependencies) ? $unpackArgs : ''));
123 
124  $checkedAgents = checkedAgents();
125  AgentSchedule($jobId, $uploadId, $checkedAgents);
126 
127  $errorMsg = '';
128  $parmAgentList = MenuHook::getAgentPluginNames("ParmAgents");
129  $plainAgentList = MenuHook::getAgentPluginNames("Agents");
130  $agentList = array_merge($plainAgentList, $parmAgentList);
131 
132  $this->rearrangeDependencies($parmAgentList);
133 
134  foreach ($parmAgentList as $parmAgent) {
135  $agent = plugin_find($parmAgent);
136  $agent->scheduleAgent($jobId, $uploadId, $errorMsg, $request, $agentList);
137  }
138 
139  $status = GetRunnableJobList();
140  $message = empty($status) ? _("Is the scheduler running? ") : "";
141  $jobUrl = Traceback_uri() . "?mod=showjobs&upload=$uploadId";
142  $message .= _("The file") . " " . $fileName . " " . _("has been uploaded. It is") .
143  ' <a href=' . $jobUrl . '>upload #' . $uploadId . "</a>.\n";
144  if ($request->get('public')==self::PUBLIC_GROUPS) {
145  $this->getObject('dao.upload.permission')->makeAccessibleToAllGroupsOf($uploadId, $userId);
146  }
147  return $message;
148  }
149 
159  function str_contains_notescaped_char($str, $char)
160  {
161  $pos = 0;
162  while ($pos < strlen($str) &&
163  ($pos = strpos($str,$char,$pos)) !== false) {
164  foreach (range(($pos++) -1, 1, -2) as $tpos) {
165  if ($tpos > 0 && $str[$tpos] !== '\\') {
166  break;
167  }
168  if ($tpos > 1 && $str[$tpos - 1] !== '\\') {
169  continue 2;
170  }
171  }
172  return true;
173  }
174  return false;
175  }
176 
184  function path_is_pattern($path)
185  {
186  return $this->str_contains_notescaped_char($path, '*')
187  || $this->str_contains_notescaped_char($path, '?')
188  || $this->str_contains_notescaped_char($path, '[')
189  || $this->str_contains_notescaped_char($path, '{');
190  }
191 
200  protected function path_can_escape($path)
201  {
202  return $this->str_contains_notescaped_char($path, '$')
203  || strpos($path,'..') !== false;
204  }
205 
216  function normalize_path($path, $host="localhost", $appendix="")
217  {
218  if (strpos($path,'/') === false || $path === '/') {
219  return false;
220  }
221  if ($this->path_is_pattern($path)) {
222  $bpath = basename($path);
223  if ($this->path_can_escape($bpath)) {
224  return false;
225  }
226 
227  if (strcmp($host,"localhost") === 0) {
228  return $this->normalize_path(dirname($path),
229  $host,
230  $bpath . ($appendix == '' ?
231  '' :
232  '/' . $appendix));
233  } else {
234  if ($this->path_can_escape($path)) {
235  return false;
236  }
237  return $path . ($appendix == '' ?
238  '' :
239  '/' . $appendix);
240  }
241  } else {
242  $rpath = realpath($path);
243  if ($rpath === false) {
244  return false;
245  }
246  return $rpath . ($appendix == '' ?
247  '' :
248  '/' . $appendix);
249  }
250  }
251 
252  function basicShEscaping($str)
253  {
254  $str = str_replace('\\', '\\\\', $str);
255  $str = str_replace('"', '\"', $str);
256  $str = str_replace('`', '\`', $str);
257  $str = str_replace('$', '\$', $str);
258  return $str;
259  }
260 
266  private function rearrangeDependencies(&$parmList)
267  {
268  $deciderKey = array_search('agent_decider', $parmList);
269  $reuserKey = array_search('agent_reuser', $parmList);
270  if ($deciderKey !== false && $reuserKey !== false) {
271  $temp = $parmList[$deciderKey];
272  $parmList[$deciderKey] = $parmList[$reuserKey];
273  $parmList[$reuserKey] = $temp;
274  }
275  }
276 }
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