FOSSology  3.2.0rc1
Open Source License Compliance by Open Source Software
UploadPageBase.php
1 <?php
2 /***********************************************************
3  * Copyright (C) 2015 Siemens AG
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * version 2 as published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  ***********************************************************/
18 
19 namespace Fossology\UI\Page;
20 
27 use Monolog\Logger;
29 
30 abstract class UploadPageBase extends DefaultPlugin
31 {
32  const NAME = "upload_file";
33  const FOLDER_PARAMETER_NAME = 'folder';
34 
35  const DESCRIPTION_INPUT_NAME = 'descriptionInputName';
36  const DESCRIPTION_VALUE = 'descriptionValue';
37  const UPLOAD_FORM_BUILD_PARAMETER_NAME = 'uploadformbuild';
38  const PUBLIC_ALL = 'public';
39  const PUBLIC_GROUPS = 'protected';
40 
42  private $folderDao;
44  private $uploadDao;
46  private $logger;
47 
48  public function __construct($name, $parameters = array())
49  {
50  parent::__construct($name, $parameters);
51 
52  $this->folderDao = $this->getObject('dao.folder');
53  $this->uploadDao = $this->getObject('dao.upload');
54  $this->logger = $this->getObject('logger');
55  }
56  abstract protected function handleUpload(Request $request);
57  abstract protected function handleView(Request $request, $vars);
58 
59  protected function handle(Request $request)
60  {
61  // Handle request
62  $this->folderDao->ensureTopLevelFolder();
63 
64  $message = "";
65  $description = "";
66  if ($request->isMethod(Request::METHOD_POST)) {
67  list($success, $message, $description) = $this->handleUpload($request);
68  }
69  $vars['message'] = $message;
70  $vars['descriptionInputValue'] = $description ?: "";
71  $vars['descriptionInputName'] = self::DESCRIPTION_INPUT_NAME;
72  $vars['folderParameterName'] = self::FOLDER_PARAMETER_NAME;
73  $vars['upload_max_filesize'] = ini_get('upload_max_filesize');
74  $vars['agentCheckBoxMake'] = '';
75 
76  $rootFolder = $this->folderDao->getRootFolder(Auth::getUserId());
77  $folderStructure = $this->folderDao->getFolderStructure($rootFolder->getId());
78 
79  $vars['folderStructure'] = $folderStructure;
80  $vars['baseUrl'] = $request->getBaseUrl();
81  $vars['moduleName'] = $this->getName();
82  $vars[self::FOLDER_PARAMETER_NAME] = $request->get(self::FOLDER_PARAMETER_NAME);
83 
84  $parmAgentList = MenuHook::getAgentPluginNames("ParmAgents");
85  $vars['parmAgentContents'] = array();
86  $vars['parmAgentFoots'] = array();
87  foreach ($parmAgentList as $parmAgent) {
88  $agent = plugin_find($parmAgent);
89  $vars['parmAgentContents'][] = $agent->renderContent($vars);
90  $vars['parmAgentFoots'][] = $agent->renderFoot($vars);
91  }
92 
93  $session = $request->getSession();
94  $session->set(self::UPLOAD_FORM_BUILD_PARAMETER_NAME, time().':'.$_SERVER['REMOTE_ADDR']);
95  $vars['uploadFormBuild'] = $session->get(self::UPLOAD_FORM_BUILD_PARAMETER_NAME);
96  $vars['uploadFormBuildParameterName'] = self::UPLOAD_FORM_BUILD_PARAMETER_NAME;
97 
98  if (@$_SESSION[Auth::USER_LEVEL] >= PLUGIN_DB_WRITE) {
99  $skip = array("agent_unpack", "agent_adj2nest", "wget_agent");
100  $vars['agentCheckBoxMake'] = AgentCheckBoxMake(-1, $skip);
101  }
102  return $this->handleView($request, $vars);
103  }
104 
105  protected function postUploadAddJobs(Request $request, $fileName, $uploadId, $jobId = null, $wgetDependency = false)
106  {
107  $userId = Auth::getUserId();
108  $groupId = Auth::getGroupId();
109 
110  if ($jobId === null) {
111  $jobId = JobAddJob($userId, $groupId, $fileName, $uploadId);
112  }
113  $dummy = "";
114  $unpackArgs = intval($request->get('scm')) == 1 ? '-I' : '';
115  $adj2nestDependencies = array();
116  if ($wgetDependency) {
117  $adj2nestDependencies = array(array('name'=>'agent_unpack','args'=>$unpackArgs,AgentPlugin::PRE_JOB_QUEUE=>array('wget_agent')));
118  }
119  $adj2nestplugin = \plugin_find('agent_adj2nest');
120  $adj2nestplugin->AgentAdd($jobId, $uploadId, $dummy, $adj2nestDependencies, null, (empty($adj2nestDependencies) ? $unpackArgs : ''));
121 
122  $checkedAgents = checkedAgents();
123  AgentSchedule($jobId, $uploadId, $checkedAgents);
124 
125  $errorMsg = '';
126  $parmAgentList = MenuHook::getAgentPluginNames("ParmAgents");
127  $plainAgentList = MenuHook::getAgentPluginNames("Agents");
128  $agentList = array_merge($plainAgentList, $parmAgentList);
129 
130  $this->rearrangeDependencies($parmAgentList);
131 
132  foreach ($parmAgentList as $parmAgent) {
133  $agent = plugin_find($parmAgent);
134  $agent->scheduleAgent($jobId, $uploadId, $errorMsg, $request, $agentList);
135  }
136 
137  $status = GetRunnableJobList();
138  $message = empty($status) ? _("Is the scheduler running? ") : "";
139  $jobUrl = Traceback_uri() . "?mod=showjobs&upload=$uploadId";
140  $message .= _("The file") . " " . $fileName . " " . _("has been uploaded. It is") .
141  ' <a href=' . $jobUrl . '>upload #' . $uploadId . "</a>.\n";
142  if ($request->get('public')==self::PUBLIC_GROUPS) {
143  $this->getObject('dao.upload.permission')->makeAccessibleToAllGroupsOf($uploadId, $userId);
144  }
145  return $message;
146  }
147 
157  function str_contains_notescaped_char($str, $char)
158  {
159  $pos = 0;
160  while ($pos < strlen($str) &&
161  ($pos = strpos($str,$char,$pos)) !== false) {
162  foreach (range(($pos++) -1, 1, -2) as $tpos) {
163  if ($tpos > 0 && $str[$tpos] !== '\\') {
164  break;
165  }
166  if ($tpos > 1 && $str[$tpos - 1] !== '\\') {
167  continue 2;
168  }
169  }
170  return true;
171  }
172  return false;
173  }
174 
182  function path_is_pattern($path)
183  {
184  return $this->str_contains_notescaped_char($path, '*')
185  || $this->str_contains_notescaped_char($path, '?')
186  || $this->str_contains_notescaped_char($path, '[')
187  || $this->str_contains_notescaped_char($path, '{');
188  }
189 
198  protected function path_can_escape($path)
199  {
200  return $this->str_contains_notescaped_char($path, '$')
201  || strpos($path,'..') !== false;
202  }
203 
214  function normalize_path($path, $host="localhost", $appendix="")
215  {
216  if (strpos($path,'/') === false || $path === '/') {
217  return false;
218  }
219  if ($this->path_is_pattern($path)) {
220  $bpath = basename($path);
221  if ($this->path_can_escape($bpath)) {
222  return false;
223  }
224 
225  if (strcmp($host,"localhost") === 0) {
226  return $this->normalize_path(dirname($path),
227  $host,
228  $bpath . ($appendix == '' ?
229  '' :
230  '/' . $appendix));
231  } else {
232  if ($this->path_can_escape($path)) {
233  return false;
234  }
235  return $path . ($appendix == '' ?
236  '' :
237  '/' . $appendix);
238  }
239  } else {
240  $rpath = realpath($path);
241  if ($rpath === false) {
242  return false;
243  }
244  return $rpath . ($appendix == '' ?
245  '' :
246  '/' . $appendix);
247  }
248  }
249 
250  function basicShEscaping($str)
251  {
252  $str = str_replace('\\', '\\\\', $str);
253  $str = str_replace('"', '\"', $str);
254  $str = str_replace('`', '\`', $str);
255  $str = str_replace('$', '\$', $str);
256  return $str;
257  }
258 
264  private function rearrangeDependencies(&$parmList)
265  {
266  $deciderKey = array_search('agent_decider', $parmList);
267  $reuserKey = array_search('agent_reuser', $parmList);
268  if ($deciderKey !== false && $reuserKey !== false) {
269  $temp = $parmList[$deciderKey];
270  $parmList[$deciderKey] = $parmList[$reuserKey];
271  $parmList[$reuserKey] = $temp;
272  }
273  }
274 }
GetRunnableJobList()
Get runnable job list, the process is below:
AgentSchedule($jobId, $uploadId, $agents)
Schedule all given agents.
checkedAgents()
read the UI form and return array of user selected agents Because input comes from the user...
Traceback_uri()
Get the URI without query to this location.
static getUserId()
Get the current user&#39;s id.
Definition: Auth.php:69
normalize_path($path, $host="localhost", $appendix="")
normalizes an path and returns FALSE on errors
AgentCheckBoxMake($upload_pk, $SkipAgents=array(), $specified_username="")
Generate a checkbox list of available agents.
static getAgentPluginNames($hook='Agents')
Definition: MenuHook.php:27
path_can_escape($path)
checks, whether a path contains substrings, which could enable it to escape his prefix ...
path_is_pattern($path)
checks, whether a path is a pattern from the perspective of a shell
plugin_find($pluginName)
Given the official name of a plugin, return the $Plugins object.
#define PLUGIN_DB_WRITE
Plugin requires write permission on DB.
Definition: libfossology.h:50
list_t type structure used to keep various lists. (e.g. there are multiple lists).
Definition: nomos.h:321
static getGroupId()
Get the current user&#39;s group id.
Definition: Auth.php:78
str_contains_notescaped_char($str, $char)
checks, whether a string contains some special character without escaping