FOSSology  4.4.0
Open Source License Compliance by Open Source Software
UploadFilePage.php
1 <?php
2 /*
3  SPDX-FileCopyrightText: © 2008-2013 Hewlett-Packard Development Company, L.P.
4  SPDX-FileCopyrightText: © 2014-2017 Siemens AG
5 
6  SPDX-License-Identifier: GPL-2.0-only
7 */
8 
9 namespace Fossology\UI\Page;
10 
14 use Symfony\Component\HttpFoundation\File\Exception\FileException;
15 use Symfony\Component\HttpFoundation\File\UploadedFile;
16 use Symfony\Component\HttpFoundation\Request;
17 use Symfony\Component\HttpFoundation\Response;
18 
23 {
24  const FILE_INPUT_NAME = 'fileInput';
25 
26 
27  public function __construct()
28  {
29  parent::__construct(self::NAME, array(
30  self::TITLE => _("Upload a New File"),
31  self::MENU_LIST => "Upload::From File",
32  self::DEPENDENCIES => array("agent_unpack", "showjobs"),
33  self::PERMISSION => Auth::PERM_WRITE
34  ));
35  }
36 
37 
43  protected function handleView(Request $request, $vars)
44  {
45  // Recalculate views for reuse agent to support multi file uploads
46  $parmAgentList = MenuHook::getAgentPluginNames("ParmAgents");
47  $vars['parmAgentContents'] = array();
48  $vars['parmAgentFoots'] = array();
49  $vars['hiddenAgentContents'] = array();
50  foreach ($parmAgentList as $parmAgent) {
51  $agent = plugin_find($parmAgent);
52  if ($parmAgent == "agent_reuser") {
53  $vars['parmAgentContents'][] = sprintf("<li>
54  <div class='form-group'>
55  <label for='reuse'>
56  (%s) %s
57  </label>
58  <img src='images/info_16.png' data-toggle='tooltip' title='%s' alt='' class='info-bullet'/><br/>
59  <button type='button' class='btn btn-default btn-sm' data-toggle='modal' data-target='#reuseModal'>%s</button>
60  <img src='images/info_16.png' data-toggle='tooltip' title='%s' alt='' class='info-bullet'/><br/>
61 </li>", _("Optional"), _("Reuse"),
62  _("Copy clearing decisions if there is the same file hash between two files"),
63  _("Set the reuse information"),
64  _("Open the pop-up to setup the reuse information for uploads"));
65  $vars['hiddenAgentContents'][] = $agent->renderContent($vars);
66  } else {
67  $vars['parmAgentContents'][] = $agent->renderContent($vars);
68  }
69  $vars['parmAgentFoots'][] = $agent->renderFoot($vars);
70  }
71  $vars['fileInputName'] = self::FILE_INPUT_NAME;
72  return $this->render("upload_file.html.twig", $this->mergeWithDefault($vars));
73  }
74 
78  protected function handleUpload(Request $request)
79  {
80  global $MODDIR;
81  global $SYSCONFDIR;
82  define("UPLOAD_ERR_EMPTY", 5);
83  define("UPLOAD_ERR_INVALID_FOLDER_PK", 100);
84  define("UPLOAD_ERR_RESEND", 200);
85  $uploadErrors = array(
86  UPLOAD_ERR_OK => _("No errors."),
87  UPLOAD_ERR_INI_SIZE => _("Larger than upload_max_filesize ") . ini_get('upload_max_filesize'),
88  UPLOAD_ERR_FORM_SIZE => _("Larger than form MAX_FILE_SIZE."),
89  UPLOAD_ERR_PARTIAL => _("Partial upload."),
90  UPLOAD_ERR_NO_FILE => _("No file selected."),
91  UPLOAD_ERR_NO_TMP_DIR => _("No temporary directory."),
92  UPLOAD_ERR_CANT_WRITE => _("Can't write to disk."),
93  UPLOAD_ERR_EXTENSION => _("File upload stopped by extension."),
94  UPLOAD_ERR_EMPTY => _("File is empty or you don't have permission to read the file."),
95  UPLOAD_ERR_INVALID_FOLDER_PK => _("Invalid Folder."),
96  UPLOAD_ERR_RESEND => _("This seems to be a resent file.")
97  );
98 
99  $folderId = intval($request->get(self::FOLDER_PARAMETER_NAME));
100  $descriptions = $request->get(self::DESCRIPTION_INPUT_NAME, []);
101  for ($i = 0; $i < count($descriptions); $i++) {
102  $descriptions[$i] = stripslashes($descriptions[$i]);
103  $descriptions[$i] = $this->basicShEscaping($descriptions[$i]);
104  }
105  $uploadedFiles = $request->files->get(self::FILE_INPUT_NAME, []);
106  $uploadFiles = [];
107  for ($i = 0; $i < count($uploadedFiles); $i++) {
108  $uploadFiles[] = [
109  'file' => $uploadedFiles[$i],
110  'description' => $descriptions[$i]
111  ];
112  }
113 
114  if (empty($uploadedFiles)) {
115  return array(false, $uploadErrors[UPLOAD_ERR_NO_FILE], "");
116  }
117 
118  if (
119  $request->getSession()->get(self::UPLOAD_FORM_BUILD_PARAMETER_NAME)
120  != $request->get(self::UPLOAD_FORM_BUILD_PARAMETER_NAME)
121  ) {
122  return array(false, $uploadErrors[UPLOAD_ERR_RESEND], "");
123  }
124 
125  foreach ($uploadFiles as $uploadedFile) {
126  if (
127  $uploadedFile['file']->getSize() == 0 &&
128  $uploadedFile['file']->getError() == 0
129  ) {
130  return array(false, $uploadErrors[UPLOAD_ERR_EMPTY], "");
131  } else if ($uploadedFile['file']->getSize() >= UploadedFile::getMaxFilesize()) {
132  return array(false, $uploadErrors[UPLOAD_ERR_INI_SIZE] .
133  _(" is really ") . $uploadedFile['file']->getSize() . " bytes.", "");
134  }
135  if (!$uploadedFile['file']->isValid()) {
136  return array(false, $uploadedFile['file']->getErrorMessage(), "");
137  }
138  }
139 
140  if (empty($folderId)) {
141  return array(false, $uploadErrors[UPLOAD_ERR_INVALID_FOLDER_PK], "");
142  }
143 
144  $setGlobal = ($request->get('globalDecisions')) ? 1 : 0;
145 
146  $public = $request->get('public');
147  $publicPermission = ($public == self::PUBLIC_ALL) ? Auth::PERM_READ : Auth::PERM_NONE;
148 
149  $uploadMode = (1 << 3); // code for "it came from web upload"
150  $userId = Auth::getUserId();
151  $groupId = Auth::getGroupId();
152  $projectGroup = $GLOBALS['SysConf']['DIRECTORIES']['PROJECTGROUP'] ?: 'fossy';
153 
154  $errors = [];
155  $success = [];
156  foreach ($uploadFiles as $uploadedFile) {
157  $originalFileName = $uploadedFile['file']->getClientOriginalName();
158  $originalFileName = $this->basicShEscaping($originalFileName);
159  /* Create an upload record. */
160  $uploadId = JobAddUpload($userId, $groupId, $originalFileName,
161  $originalFileName, $uploadedFile['description'], $uploadMode,
162  $folderId, $publicPermission, $setGlobal);
163  if (empty($uploadId)) {
164  $errors[] = _("Failed to insert upload record: ") .
165  $originalFileName;
166  continue;
167  }
168 
169  try {
170  $uploadedTempFile = $uploadedFile['file']->move(
171  $uploadedFile['file']->getPath(),
172  $uploadedFile['file']->getFilename() . '-uploaded'
173  )->getPathname();
174  } catch (FileException $e) {
175  $errors[] = _("Could not save uploaded file: ") . $originalFileName;
176  continue;
177  }
178  $success[] = [
179  "tempfile" => $uploadedTempFile,
180  "orignalfile" => $originalFileName,
181  "uploadid" => $uploadId
182  ];
183  }
184 
185  if (!empty($errors)) {
186  return [false, implode(" ; ", $errors), ""];
187  }
188 
189  $messages = [];
190  foreach ($success as $row) {
191  $uploadedTempFile = $row["tempfile"];
192  $originalFileName = $row["orignalfile"];
193  $uploadId = $row["uploadid"];
194 
195  $wgetAgentCall = "$MODDIR/wget_agent/agent/wget_agent -C -g " .
196  "$projectGroup -k $uploadId '$uploadedTempFile' -c '$SYSCONFDIR'";
197  $wgetOutput = array();
198  exec($wgetAgentCall, $wgetOutput, $wgetReturnValue);
199  unlink($uploadedTempFile);
200 
201  if ($wgetReturnValue != 0) {
202  $message = implode(' ', $wgetOutput);
203  if (empty($message)) {
204  $message = _("File upload failed. Error:") . $wgetReturnValue;
205  }
206  $errors[] = $message;
207  } else {
208  $reuseRequest = $this->getRequestForReuse($request, $originalFileName);
209  $messages[] = $this->postUploadAddJobs($reuseRequest, $originalFileName,
210  $uploadId);
211  }
212  }
213 
214  if (!empty($errors)) {
215  return [false, implode(" ; ", $errors), ""];
216  }
217 
218  return array(true, implode("", $messages), "",
219  array_column($success, "uploadid"));
220  }
226  private function getRequestForReuse(Request $request, string $originalFileName)
227  {
228  $reuseRequest = clone $request;
229  $reuseSelector = $reuseRequest->get(ReuserAgentPlugin::UPLOAD_TO_REUSE_SELECTOR_NAME);
230  $reuseMode = $reuseRequest->get(ReuserAgentPlugin::REUSE_MODE);
231 
232  if (is_array($reuseSelector) && array_key_exists($originalFileName, $reuseSelector)) {
233  $reuseRequest->request->set(
235  $reuseSelector[$originalFileName]
236  );
237  }
238  if (is_array($reuseMode) && array_key_exists($originalFileName, $reuseMode)) {
239  $reuseRequest->request->set(
241  $reuseMode[$originalFileName]
242  );
243  }
244  return $reuseRequest;
245  }
246 }
247 
248 register_plugin(new UploadFilePage());
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
render($templateName, $vars=null, $headers=null)
static getAgentPluginNames($hook='Agents')
Definition: MenuHook.php:16
UI element for reuser during Uploading new package.
const REUSE_MODE
Form element name for main license to reuse.
const UPLOAD_TO_REUSE_SELECTOR_NAME
Form element name for main license to reuse.
Upload a file from the users computer using the UI.
handleView(Request $request, $vars)
getRequestForReuse(Request $request, string $originalFileName)
Check if parameters exits for the request Create a new request object and update parameter expected v...
handleUpload(Request $request)
Process the upload request.
JobAddUpload($userId, $groupId, $job_name, $filename, $desc, $UploadMode, $folder_pk, $public_perm=Auth::PERM_NONE, $setGlobal=0)
Insert a new upload record, and update the foldercontents table.
Definition: common-job.php:56
plugin_find($pluginName)
Given the official name of a plugin, return the $Plugins object.