/** * \brief Delete * Creates a job to detele the folder * * \param $folderpk - the folder_pk to remove * \return NULL on success, string on failure. */ function Delete($folderpk, $Depends = NULL) { /* Can't remove top folder */ if ($folderpk == FolderGetTop()) { $text = _("Can Not Delete Root Folder"); return $text; } /* Get the folder's name */ $FolderName = FolderGetName($folderpk); /* Prepare the job: job "Delete" */ $userId = Auth::getUserId(); $groupId = Auth::getGroupId(); $jobpk = JobAddJob($userId, $groupId, "Delete Folder: {$FolderName}"); if (empty($jobpk) || $jobpk < 0) { $text = _("Failed to create job record"); return $text; } /* Add job: job "Delete" has jobqueue item "delagent" */ $jqargs = "DELETE FOLDER {$folderpk}"; $jobqueuepk = JobQueueAdd($jobpk, "delagent", $jqargs, NULL, NULL); if (empty($jobqueuepk)) { $text = _("Failed to place delete in job queue"); return $text; } /* Tell the scheduler to check the queue. */ $success = fo_communicate_with_scheduler("database", $output, $error_msg); if (!$success) { return $error_msg . "\n" . $output; } return NULL; }
public function Output() { $V = ""; /* If this is a POST, then process the request. */ $groupname = GetParm('groupname', PARM_TEXT); if (!empty($groupname)) { try { /* @var $userDao UserDao */ $userDao = $GLOBALS['container']->get('dao.user'); $groupId = $userDao->addGroup($groupname); $userDao->addGroupMembership($groupId, Auth::getUserId()); $text = _("Group"); $text1 = _("added"); $this->vars['message'] = "{$text} {$groupname} {$text1}."; } catch (Exception $e) { $this->vars['message'] = $e->getMessage(); } } /* Build HTML form */ $text = _("Add a Group"); $V .= "<h4>{$text}</h4>\n"; $V .= "<form name='formy' method='POST' action=" . Traceback_uri() . "?mod=group_add>\n"; $Val = htmlentities(GetParm('groupname', PARM_TEXT), ENT_QUOTES); $text = _("Enter the groupname:"); $V .= "{$text}\n"; $V .= "<input type='text' value='{$Val}' name='groupname' size=20>\n"; $text = _("Add"); $V .= "<input type='submit' value='{$text}'>\n"; $V .= "</form>\n"; return $V; }
/** * @param Request $request * @throws \Exception * @return Response */ protected function handle(Request $request) { $rf = intval($request->get('rf')); $userId = Auth::getUserId(); $groupId = Auth::getGroupId(); /** @var UserDao */ $userDao = $this->getObject('dao.user'); $canEdit = $userDao->isAdvisorOrAdmin($userId, $groupId); if (empty($rf) || !$canEdit) { $vars = array('aaData' => json_encode($this->getArrayArrayData($groupId, $canEdit)), 'canEdit' => $canEdit); return $this->render('advice_license.html.twig', $this->mergeWithDefault($vars)); } $vars = $this->getDataRow($groupId, $rf); if ($vars === false) { return $this->flushContent(_('invalid license candidate')); } if ($request->get('save')) { try { $vars = $this->saveInput($request, $vars); $vars['message'] = 'Successfully updated.'; } catch (\Exception $e) { $vars = array('rf_shortname' => $request->get('shortname'), 'rf_fullname' => $request->get('fullname'), 'rf_text' => $request->get('rf_text'), 'rf_url' => $request->get('url'), 'rf_notes' => $request->get('note'), 'rf_risk' => intval($request->get('risk'))); $vars['message'] = $e->getMessage(); } } return $this->render('advice_license-edit.html.twig', $this->mergeWithDefault($vars)); }
protected function getJobAndJobqueue($groupId, $upload, $addUploads) { $uploadId = $upload->getId(); $readMeOssAgent = plugin_find('agent_readmeoss'); $userId = Auth::getUserId(); $jqCmdArgs = $readMeOssAgent->uploadsAdd($addUploads); $dbManager = $this->getObject('db.manager'); $sql = 'SELECT jq_pk,job_pk FROM jobqueue, job ' . 'WHERE jq_job_fk=job_pk AND jq_type=$1 AND job_group_fk=$4 AND job_user_fk=$3 AND jq_args=$2 AND jq_endtime IS NULL'; $params = array($readMeOssAgent->AgentName, $uploadId, $userId, $groupId); $log = __METHOD__; if ($jqCmdArgs) { $sql .= ' AND jq_cmd_args=$5'; $params[] = $jqCmdArgs; $log .= '.args'; } else { $sql .= ' AND jq_cmd_args IS NULL'; } $scheduled = $dbManager->getSingleRow($sql, $params, $log); if (!empty($scheduled)) { return array($scheduled['job_pk'], $scheduled['jq_pk']); } $jobId = JobAddJob($userId, $groupId, $upload->getFilename(), $uploadId); $error = ""; $jobQueueId = $readMeOssAgent->AgentAdd($jobId, $uploadId, $error, array(), $jqCmdArgs); if ($jobQueueId < 0) { throw new Exception(_("Cannot schedule") . ": " . $error); } return array($jobId, $jobQueueId); }
/** * \brief queue the job * * \param * \returns status string **/ function QueueJob() { global $SysConf; /* Find all the maintagent options specified by the user. * They look like _REQUEST["a"] = "a", _REQUEST["b"]="b", ... */ $options = "-"; foreach ($_REQUEST as $key => $value) { if ($key == $value) { $options .= $value; } } /* Create the maintenance job */ $user_pk = Auth::getUserId(); $groupId = Auth::getGroupId(); $job_pk = JobAddJob($user_pk, $groupId, "Maintenance"); if (empty($job_pk) || $job_pk < 0) { return _("Failed to insert job record"); } $jq_pk = JobQueueAdd($job_pk, "maintagent", NULL, NULL, NULL, NULL, $options); if (empty($jq_pk)) { return _("Failed to insert task 'Maintenance' into job queue"); } /* Tell the scheduler to check the queue. */ $success = fo_communicate_with_scheduler("database", $output, $error_msg); if (!$success) { return $error_msg . "\n" . $output; } return _("The maintenance job has been queued"); }
/** * @param Request $request * @return Response */ protected function handle(Request $request) { $userId = Auth::getUserId(); $vars = array(); /** @var UserDao $userDao */ $userDao = $this->getObject('dao.user'); $groupMap = $userDao->getDeletableAdminGroupMap($userId, $_SESSION[Auth::USER_LEVEL]); $groupId = $request->get('grouppk'); if (!empty($groupId)) { try { $userDao->deleteGroup($groupId); $vars['message'] = _("Group") . ' ' . $groupMap[$groupId] . ' ' . _("deleted") . '.'; unset($groupMap[$groupId]); } catch (\Exception $e) { $vars['message'] = $e->getMessage(); } } if (empty($groupMap)) { $vars['content'] = _("You have no groups you can delete."); return $this->render('include/base.html.twig', $this->mergeWithDefault($vars)); } $vars['groupMap'] = $groupMap; $vars['uri'] = Traceback_uri() . "?mod=group_delete"; $vars['groupMap'] = $groupMap; return $this->render('admin_group_delete.html.twig', $this->mergeWithDefault($vars)); }
protected function handleUpload(Request $request) { $folderId = intval($request->get(self::FOLDER_PARAMETER_NAME)); $description = stripslashes($request->get(self::DESCRIPTION_INPUT_NAME)); $description = $this->basicShEscaping($description); $getUrlThatMightIncludeSpaces = trim($request->get(self::GETURL_PARAM)); $getURL = str_replace(" ", "%20", $getUrlThatMightIncludeSpaces); if (empty($getURL)) { return array(false, _("Invalid URL"), $description); } if (preg_match("@^((http)|(https)|(ftp))://([[:alnum:]]+)@i", $getURL) != 1) { return array(false, _("Invalid URL"), $description); } $getUrl = $this->basicShEscaping($getUrl); $name = $request->get(self::NAME_PARAM); if (empty($name)) { $name = basename($getURL); } $shortName = basename($name); if (empty($shortName)) { $shortName = $name; } /* Create an upload record. */ $mode = 1 << 2; // code for "it came from wget" $userId = Auth::getUserId(); $groupId = Auth::getGroupId(); $public = $request->get('public'); $publicPermission = $public == self::PUBLIC_ALL ? Auth::PERM_READ : Auth::PERM_NONE; $uploadId = JobAddUpload($userId, $groupId, $shortName, $getURL, $description, $mode, $folderId, $publicPermission); if (empty($uploadId)) { $text = _("Failed to insert upload record"); return array(false, $text, $description); } $level = intval($request->get(self::LEVEL_PARAM)); if ($level < 0) { $level = 1; } /* first trim, then get rid of whitespaces before and after each comma letter */ $accept = preg_replace('/\\s*,\\s*/', ',', trim($request->get(self::ACCEPT_PARAM))); $accept = $this->basicShEscaping($accept); $reject = preg_replace('/\\s*,\\s*/', ',', trim($request->get(self::REJECT_PARAM))); $reject = $this->basicShEscaping($reject); /* Create the job: job "wget" */ $jobId = JobAddJob($userId, $groupId, "wget", $uploadId); if (empty($jobId) || $jobId < 0) { return array(false, _("Failed to insert job record"), $description); } $jqArgs = "{$uploadId} - {$getURL} -l {$level} "; if (!empty($accept)) { $jqArgs .= "-A {$accept} "; } $jqArgs .= empty($reject) ? "-R index.html* " : "-R {$reject},index.html* "; $jobqueueId = JobQueueAdd($jobId, "wget_agent", $jqArgs, NULL, NULL); if (empty($jobqueueId)) { return array(false, "Failed to insert task 'wget_agent' into job queue", $description); } $message = $this->postUploadAddJobs($request, $shortName, $uploadId, $jobId, $jobqueueId); return array(true, $message, $description); }
/** * @param Request $request * @return Response */ protected function handle(Request $request) { $userId = Auth::getUserId(); $vars = array(); $folderContentId = intval($request->get('foldercontent')); $parentFolderId = intval($request->get('toFolder')); if ($folderContentId && $parentFolderId && $request->get('copy')) { try { $this->folderDao->copyContent($folderContentId, $parentFolderId); } catch (Exception $ex) { $vars['message'] = $ex->getMessage(); } } elseif ($folderContentId && $parentFolderId) { try { $this->folderDao->moveContent($folderContentId, $parentFolderId); } catch (Exception $ex) { $vars['message'] = $ex->getMessage(); } } $rootFolderId = $this->folderDao->getRootFolder($userId)->getId(); /* @var $uiFolderNav FolderNav */ $uiFolderNav = $this->getObject('ui.folder.nav'); $vars['folderTree'] = $uiFolderNav->showFolderTree($rootFolderId); $vars['folderStructure'] = $this->folderDao->getFolderStructure($rootFolderId); return $this->render('admin_content_move.html.twig', $this->mergeWithDefault($vars)); }
/** * \brief Given a folder_pk, add a job. * \param $uploadpk - the upload(upload_id) you want to delete * \param $Depends - Depends is not used for now * * \return NULL on success, string on failure. */ function Delete($uploadpk, $Depends = NULL) { global $SysConf; /* Prepare the job: job "Delete" */ $user_pk = Auth::getUserId(); $group_pk = Auth::getGroupId(); $jobpk = JobAddJob($user_pk, $group_pk, "Delete", $uploadpk); if (empty($jobpk) || $jobpk < 0) { $text = _("Failed to create job record"); return $text; } /* Add job: job "Delete" has jobqueue item "delagent" */ $jqargs = "DELETE UPLOAD {$uploadpk}"; $jobqueuepk = JobQueueAdd($jobpk, "delagent", $jqargs, NULL, NULL); if (empty($jobqueuepk)) { $text = _("Failed to place delete in job queue"); return $text; } /* Tell the scheduler to check the queue. */ $success = fo_communicate_with_scheduler("database", $output, $error_msg); if (!$success) { $error_msg = _("Is the scheduler running? Your jobs have been added to job queue."); $URL = Traceback_uri() . "?mod=showjobs&upload={$uploadpk} "; $LinkText = _("View Jobs"); $msg = "{$error_msg} <a href={$URL}>{$LinkText}</a>"; return $msg; } return NULL; }
/** * @brief Allow user to change their account settings (users db table). * If the user is an Admin, they can change settings for any user.\n * This is called in the following circumstances:\n * 1) User clicks on Admin > Edit User Account\n * 2) User has chosen a user to edit from the 'userid' select list \n * 3) User hit submit to update user data\n */ protected function handle(Request $request) { /* Is the session owner an admin? */ $user_pk = Auth::getUserId(); $SessionUserRec = $this->GetUserRec($user_pk); $SessionIsAdmin = $this->IsSessionAdmin($SessionUserRec); $user_pk_to_modify = intval($request->get('user_pk')); if (!($SessionIsAdmin or empty($user_pk_to_modify) or $user_pk == $user_pk_to_modify)) { $vars['content'] = _("Your request is not valid."); return $this->render('include/base.html.twig', $this->mergeWithDefault($vars)); } $vars = array('refreshUri' => Traceback_uri() . "?mod=" . self::NAME); /* If this is a POST (the submit button was clicked), then process the request. */ $BtnText = $request->get('UpdateBtn'); if (!empty($BtnText)) { /* Get the form data to in an associated array */ $UserRec = $this->CreateUserRec($request, ""); $rv = $this->UpdateUser($UserRec, $SessionIsAdmin); if (empty($rv)) { // Successful db update $vars['message'] = "User {$UserRec['user_name']} updated."; /* Reread the user record as update verification */ $UserRec = $this->CreateUserRec($request, $UserRec['user_pk']); } else { $vars['message'] = $rv; } } else { $NewUserpk = intval($request->get('newuser')); $UserRec = empty($NewUserpk) ? $this->CreateUserRec($request, $user_pk) : $this->CreateUserRec($request, $NewUserpk); } /* display the edit form with the requested user data */ $vars = array_merge($vars, $this->DisplayForm($UserRec, $SessionIsAdmin)); $vars['userId'] = $UserRec['user_pk']; return $this->render('user_edit.html.twig', $this->mergeWithDefault($vars)); }
/** * \brief Find out who I am from my user record. * \returns user name */ protected function WhoAmI() { $user_pk = Auth::getUserId(); if (empty($user_pk)) { return _("You are not logged in"); } $userDao = $this->getObject('dao.user'); return $userDao->getUserName($user_pk); }
protected function getDefaultBucketPool() { $user_pk = Auth::getUserId(); if (empty($user_pk)) { return 0; } /* @var $dbManager DbManager */ $dbManager = $GLOBALS['container']->get('db.manager'); $usersRec = $dbManager->getSingleRow('SELECT default_bucketpool_fk FROM users WHERE user_pk=$1', array($user_pk)); return $usersRec['default_bucketpool_fk']; }
/** * \brief Generate the text for this plugin. */ public function Output() { /* If this is a POST, then process the request. */ $folder = GetParm('folder', PARM_INTEGER); if (!empty($folder)) { $userId = Auth::getUserId(); $sql = "SELECT folder_name FROM folder join users on (users.user_pk = folder.user_fk or users.user_perm = 10) where folder_pk = \$1 and users.user_pk = \$2;"; $Folder = $this->dbManager->getSingleRow($sql, array($folder, $userId), __METHOD__ . "GetRowWithFolderName"); if (!empty($Folder['folder_name'])) { $rc = $this->Delete($folder, $userId); if (empty($rc)) { /* Need to refresh the screen */ $text = _("Deletion of folder "); $text1 = _(" added to job queue"); $this->vars['message'] = $text . $Folder['folder_name'] . $text1; } else { $text = _("Deletion of "); $text1 = _(" failed: "); $this->vars['message'] = $text . $Folder['folder_name'] . $text1 . $rc; } } else { $text = _("Cannot delete this folder :: Permission denied"); $this->vars['message'] = $text; } } $V = "<form method='post'>\n"; // no url = this url $text = _("Select the folder to"); $text1 = _("delete"); $V .= "{$text} <em>{$text1}</em>.\n"; $V .= "<ul>\n"; $text = _("This will"); $text1 = _("delete"); $text2 = _("the folder, all subfolders, and all uploaded files stored within the folder!"); $V .= "<li>{$text} <em>{$text1}</em> {$text2}\n"; $text = _("Be very careful with your selection since you can delete a lot of work!"); $V .= "<li>{$text}\n"; $text = _("All analysis only associated with the deleted uploads will also be deleted."); $V .= "<li>{$text}\n"; $text = _("THERE IS NO UNDELETE. When you select something to delete, it will be removed from the database and file repository."); $V .= "<li>{$text}\n"; $V .= "</ul>\n"; $text = _("Select the folder to delete: "); $V .= "<P>{$text}\n"; $V .= "<select name='folder'>\n"; $text = _("select folder"); $V .= "<option value=''>[{$text}]</option>\n"; $V .= FolderListOption(-1, 0); $V .= "</select><P />\n"; $text = _("Delete"); $V .= "<input type='submit' value='{$text}'>\n"; $V .= "</form>\n"; return $V; }
/** * * @param int $uploadTreeId * @param Request $request * @return int $jobQueueId */ private function getJobQueueId($uploadTreeId, Request $request) { $uploadEntry = $this->uploadDao->getUploadEntry($uploadTreeId); $uploadId = intval($uploadEntry['upload_fk']); $userId = Auth::getUserId(); $groupId = Auth::getGroupId(); if ($uploadId <= 0 || !$this->uploadDao->isAccessible($uploadId, $groupId)) { throw new Exception('permission denied'); } $bulkScope = $request->get('bulkScope'); switch ($bulkScope) { case 'u': $uploadTreeTable = $this->uploadDao->getUploadtreeTableName($uploadId); $topBounds = $this->uploadDao->getParentItemBounds($uploadId, $uploadTreeTable); $uploadTreeId = $topBounds->getItemId(); break; case 'f': if (!Isdir($uploadEntry['ufile_mode']) && !Iscontainer($uploadEntry['ufile_mode']) && !Isartifact($uploadEntry['ufile_mode'])) { $uploadTreeId = $uploadEntry['parent'] ?: $uploadTreeId; } break; default: throw new InvalidArgumentException('bad scope request'); } $refText = $request->get('refText'); $actions = $request->get('bulkAction'); $licenseRemovals = array(); foreach ($actions as $licenseAction) { $licenseRemovals[$licenseAction['licenseId']] = $licenseAction['action'] == 'remove'; } $bulkId = $this->licenseDao->insertBulkLicense($userId, $groupId, $uploadTreeId, $licenseRemovals, $refText); if ($bulkId <= 0) { throw new Exception('cannot insert bulk reference'); } $upload = $this->uploadDao->getUpload($uploadId); $uploadName = $upload->getFilename(); $job_pk = JobAddJob($userId, $groupId, $uploadName, $uploadId); /** @var DeciderJobAgentPlugin $deciderPlugin */ $deciderPlugin = plugin_find("agent_deciderjob"); $dependecies = array(array('name' => 'agent_monk_bulk', 'args' => $bulkId)); $conflictStrategyId = intval($request->get('forceDecision')); $errorMsg = ''; $jqId = $deciderPlugin->AgentAdd($job_pk, $uploadId, $errorMsg, $dependecies, $conflictStrategyId); if (!empty($errorMsg)) { throw new Exception(str_replace('<br>', "\n", $errorMsg)); } return $jqId; }
/** * @param Request $request * @return Response */ protected function handle(Request $request) { $userId = Auth::getUserId(); $vars = array(); $folderContentId = intval($request->get('foldercontent')); if ($folderContentId) { try { $this->folderDao->removeContent($folderContentId); } catch (Exception $ex) { $vars['message'] = $ex->getMessage(); } } $rootFolderId = $this->folderDao->getRootFolder($userId)->getId(); /* @var $uiFolderNav FolderNav */ $uiFolderNav = $GLOBALS['container']->get('ui.folder.nav'); $vars['folderTree'] = $uiFolderNav->showFolderTree($rootFolderId); return $this->render('admin_content_delete.html.twig', $this->mergeWithDefault($vars)); }
/** * \brief Display the loaded menu and plugins. */ public function Output() { global $Plugins; global $PG_CONN; $UploadPk = GetParm("upload", PARM_INTEGER); $Agent = GetParm("agent", PARM_STRING); if (empty($UploadPk) || empty($Agent)) { return new Response('missing parameter', Response::HTTP_BAD_REQUEST, array('Content-type' => 'text/plain')); } $sql = "SELECT upload_pk, upload_filename FROM upload WHERE upload_pk = '{$UploadPk}'"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); if (pg_num_rows($result) < 1) { $errMsg = __FILE__ . ":" . __LINE__ . " " . _("Upload") . " " . $UploadPk . " " . _("not found"); return new Response($errMsg, Response::HTTP_BAD_REQUEST, array('Content-type' => 'text/plain')); } $UploadRow = pg_fetch_assoc($result); $ShortName = $UploadRow['upload_filename']; pg_free_result($result); $user_pk = Auth::getUserId(); $group_pk = Auth::getGroupId(); $job_pk = JobAddJob($user_pk, $group_pk, $ShortName, $UploadPk); $Dependencies = array(); $P =& $Plugins[plugin_find_id($Agent)]; $rv = $P->AgentAdd($job_pk, $UploadPk, $ErrorMsg, $Dependencies); if ($rv <= 0) { $text = _("Scheduling of Agent(s) failed: "); return new Response($text . $rv . $ErrorMsg, Response::HTTP_BAD_REQUEST, array('Content-type' => 'text/plain')); } /** check if the scheudler is running */ $status = GetRunnableJobList(); $scheduler_msg = ""; if (empty($status)) { $scheduler_msg .= _("Is the scheduler running? "); } $URL = Traceback_uri() . "?mod=showjobs&upload={$UploadPk}"; /* Need to refresh the screen */ $text = _("Your jobs have been added to job queue."); $LinkText = _("View Jobs"); $msg = "{$scheduler_msg}" . "{$text} <a href={$URL}>{$LinkText}</a>"; $this->vars['message'] = $msg; return new Response($msg, Response::HTTP_OK, array('Content-type' => 'text/plain')); }
/** * @brief Display the loaded menu and plugins. */ protected function handle(Request $request) { $groupId = Auth::getGroupId(); $gup = $this->dbManager->getSingleRow('SELECT group_perm FROM group_user_member WHERE user_fk=$1 AND group_fk=$2', array(Auth::getUserId(), $groupId), __METHOD__ . '.user_perm'); if (!$gup) { throw new \Exception('You are assigned to wrong group.'); } $this->userPerm = $gup['group_perm']; $uploadId = intval($request->get('uploadId')); if ($uploadId && !$this->uploadDao->isAccessible($uploadId, $groupId)) { throw new \Exception('You cannot access to this upload'); } $columnName = $request->get('columnName'); $statusId = intval($request->get('statusId')); $value = intval($request->get('value')); $moveUpload = intval($request->get("move")); $beyondUpload = intval($request->get("beyond")); $commentText = $request->get('commentText'); $direction = $request->get('direction'); if (!empty($columnName) && !empty($uploadId) && !empty($value)) { $uploadBrowseProxy = new UploadBrowseProxy($groupId, $this->userPerm, $this->dbManager); $uploadBrowseProxy->updateTable($columnName, $uploadId, $value); } else { if (!empty($moveUpload) && !empty($beyondUpload)) { $uploadBrowseProxy = new UploadBrowseProxy($groupId, $this->userPerm, $this->dbManager); $uploadBrowseProxy->moveUploadBeyond($moveUpload, $beyondUpload); } else { if (!empty($uploadId) && !empty($direction)) { $uploadBrowseProxy = new UploadBrowseProxy($groupId, $this->userPerm, $this->dbManager); $uploadBrowseProxy->moveUploadToInfinity($uploadId, $direction == 'top'); } else { if (!empty($uploadId) && !empty($commentText) && !empty($statusId)) { $uploadBrowseProxy = new UploadBrowseProxy($groupId, $this->userPerm, $this->dbManager); $uploadBrowseProxy->setStatusAndComment($uploadId, $statusId, $commentText); } else { return $this->respondFolderGetTableData($request); } } } } return new Response(''); }
/** * @param array $vars * @return string */ public function renderContent(&$vars) { if (!array_key_exists('folderStructure', $vars)) { $rootFolderId = $this->folderDao->getRootFolder(Auth::getUserId())->getId(); $vars['folderStructure'] = $this->folderDao->getFolderStructure($rootFolderId); } if ($this->folderDao->isWithoutReusableFolders($vars['folderStructure'])) { return ''; } $pair = array_key_exists(self::FOLDER_PARAMETER_NAME, $vars) ? $vars[self::FOLDER_PARAMETER_NAME] : ''; list($folderId, $trustGroupId) = $this->getFolderIdAndTrustGroup($pair); if (empty($folderId) && !empty($vars['folderStructure'])) { $folderId = $vars['folderStructure'][0][FolderDao::FOLDER_KEY]->getId(); } $vars['reuseFolderSelectorName'] = self::REUSE_FOLDER_SELECTOR_NAME; $vars['folderParameterName'] = self::FOLDER_PARAMETER_NAME; $vars['uploadToReuseSelectorName'] = self::UPLOAD_TO_REUSE_SELECTOR_NAME; $vars['folderUploads'] = $this->prepareFolderUploads($folderId, $trustGroupId); $renderer = $this->getObject('twig.environment'); return $renderer->loadTemplate('agent_reuser.html.twig')->render($vars); }
/** * \brief Get the top-of-tree folder_pk for the current user. * Fail if there is no user session. * * \return folder_pk for the current user */ function GetUserRootFolder() { global $PG_CONN; /* validate inputs */ $user_pk = Auth::getUserId(); /* everyone has a user_pk, even if not logged in. But verify. */ if (empty($user_pk)) { return "__FILE__:__LINE__ GetUserRootFolder(Not logged in)<br>"; } /* Get users root folder */ $sql = "select root_folder_fk from users where user_pk={$user_pk}"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); $UsersRow = pg_fetch_assoc($result); $root_folder_fk = $UsersRow['root_folder_fk']; pg_free_result($result); if (empty($root_folder_fk)) { $text = _("Missing root_folder_fk for user "); fatal("<h2>" . $text . $user_pk . "</h2>", __FILE__, __LINE__); } return $root_folder_fk; }
/** * @brief Display the loaded menu and plugins. */ function Output() { if ($this->State != PLUGIN_STATE_READY) { return; } $itemId = $_POST['uploadTreeId']; if (empty($itemId)) { return $this->errorJson("bad item id"); } $userId = Auth::getUserId(); $groupId = Auth::getGroupId(); $decisionMark = @$_POST['decisionMark']; if (!empty($decisionMark)) { $itemTableName = $this->uploadDao->getUploadtreeTableName($itemId); /** @var ItemTreeBounds */ $itemTreeBounds = $this->uploadDao->getItemTreeBounds($itemId, $itemTableName); $errMsg = $this->clearingDao->markDirectoryAsIrrelevant($itemTreeBounds, $groupId, $userId); if (empty($errMsg)) { return new JsonResponse(array('result' => 'success')); } return $this->errorJson($errMsg, $errMsg); } return $this->doEdit($userId, $groupId, $itemId); }
protected function postUploadAddJobs(Request $request, $fileName, $uploadId, $jobId = null, $wgetDependency = false) { $userId = Auth::getUserId(); $groupId = Auth::getGroupId(); if ($jobId === null) { $jobId = JobAddJob($userId, $groupId, $fileName, $uploadId); } $dummy = ""; $adj2nestDependencies = array(); if ($wgetDependency) { $adj2nestDependencies = array(array('name' => 'agent_unpack', AgentPlugin::PRE_JOB_QUEUE => array('wget_agent'))); } $adj2nestplugin = \plugin_find('agent_adj2nest'); $adj2nestplugin->AgentAdd($jobId, $uploadId, $dummy, $adj2nestDependencies); $checkedAgents = checkedAgents(); AgentSchedule($jobId, $uploadId, $checkedAgents); $errorMsg = ''; $parmAgentList = MenuHook::getAgentPluginNames("ParmAgents"); $plainAgentList = MenuHook::getAgentPluginNames("Agents"); $agentList = array_merge($plainAgentList, $parmAgentList); foreach ($parmAgentList as $parmAgent) { $agent = plugin_find($parmAgent); $agent->scheduleAgent($jobId, $uploadId, $errorMsg, $request, $agentList); } $status = GetRunnableJobList(); $message = empty($status) ? _("Is the scheduler running? ") : ""; $jobUrl = Traceback_uri() . "?mod=showjobs&upload={$uploadId}"; $message .= _("The file") . " " . $fileName . " " . _("has been uploaded. It is") . ' <a href=' . $jobUrl . '>upload #' . $uploadId . "</a>.\n"; if ($request->get('public') == self::PUBLIC_GROUPS) { $this->getObject('dao.upload.permission')->makeAccessibleToAllGroupsOf($uploadId, $userId); } return $message; }
/** * @brief Returns an upload job status in html * @param $jobData * @return Returns an upload job status in html **/ protected function show($jobData, $page) { global $container; /** @var DbManager */ $dbManager = $container->get('db.manager'); $outBuf = ''; $pagination = ''; $numJobs = count($jobData); if ($numJobs == 0) { return array('showJobsData' => "There are no jobs to display"); } $uri = Traceback_uri() . "?mod=showjobs"; $uriFull = $uri . Traceback_parm_keep(array("upload")); $uriFullMenu = $uri . Traceback_parm_keep(array("allusers")); /* Next/Prev menu */ $next = $numJobs > $this->maxUploadsPerPage; if ($numJobs > $this->maxUploadsPerPage) { $pagination .= MenuEndlessPage($page, $next, $uriFullMenu); } /*****************************************************************/ /* Now display the summary */ /*****************************************************************/ $job = -1; $uploadStyle = "style='font:bold 10pt verdana, arial, helvetica; background:gold; color:white;'"; $noUploadStyle = "style='font:bold 10pt verdana, arial, helvetica; background:gold; color:black;'"; $jobStyle = "style='font:bold 8pt verdana, arial, helvetica; background:lavender; color:black;'"; $prevupload_pk = ""; $firstJob = $page * $this->maxUploadsPerPage; $lastJob = $page * $this->maxUploadsPerPage + $this->maxUploadsPerPage; $jobNumber = -1; /** if $single_browse is 1, represent alread has an upload browse link, if single_browse is 0, no upload browse link */ $single_browse = 0; foreach ($jobData as $job) { /* Upload */ if (!empty($job["upload"])) { $uploadName = GetArrayVal("upload_filename", $job["upload"]); $uploadDesc = GetArrayVal("upload_desc", $job["upload"]); $upload_pk = GetArrayVal("upload_pk", $job["upload"]); $jobId = GetArrayVal("job_pk", $job["job"]); /** the column pfile_fk of the record in the table(upload) is NULL when this record is inserted */ if (!empty($upload_pk) && $prevupload_pk != $upload_pk || empty($upload_pk) && 0 == $single_browse) { $prevupload_pk = $upload_pk; $jobNumber++; /* Only display the jobs for this page */ if ($jobNumber >= $lastJob) { break; } if ($jobNumber < $firstJob) { continue; } /* blank line separator between pfiles */ $outBuf .= "<tr><td colspan=8> <hr> </td></tr>"; $outBuf .= "<tr>"; $outBuf .= "<th {$uploadStyle}></th>"; $outBuf .= "<th colspan=6 {$uploadStyle}>"; if (!empty($job['uploadtree'])) { $uploadtree_pk = $job['uploadtree']['uploadtree_pk']; $outBuf .= "<a title='Click to browse' href='" . Traceback_uri() . "?mod=browse&upload=" . $job['job']['job_upload_fk'] . "&item=" . $uploadtree_pk . "'>"; } else { $outBuf .= "<a {$noUploadStyle}>"; } /* get $userName if all jobs are shown */ $userName = ""; $allusers = GetParm("allusers", PARM_INTEGER); if ($allusers > 0) { $statementName = __METHOD__ . "UploadRec"; $uploadRec = $dbManager->getSingleRow("select * from upload where upload_pk=\$1", array($job['job']['job_upload_fk']), $statementName); if (!empty($uploadRec['user_fk'])) { $statementName = __METHOD__ . "UserRec"; $userRec = $dbManager->getSingleRow("select * from users where user_pk=\$1", array($uploadRec['user_fk']), $statementName); $userName = "******"; } else { $statementName = __METHOD__ . "UserRec1"; $userRec = $dbManager->getSingleRow("select * from users where user_pk=\$1", array($job['job']['job_user_fk']), $statementName); $userName = "******"; } } $outBuf .= $uploadName . $userName; if (!empty($uploadDesc)) { $outBuf .= " (" . $uploadDesc . ")"; } $outBuf .= "</a>"; $outBuf .= "</th>"; $outBuf .= "<th {$uploadStyle}><a>" . $this->showJobsDao->getEstimatedTime($jobId) . "</a></th>"; $outBuf .= "</tr>"; $single_browse = 1; } else { if ($jobNumber < $firstJob) { continue; } } } else { /* Show Jobs that are not attached to an upload */ $jobNumber++; /* Only display the jobs for this page */ if ($jobNumber >= $lastJob) { break; } if ($jobNumber < $firstJob) { continue; } /* blank line separator between pfiles */ $outBuf .= "<tr><td colspan=8> <hr> </td></tr>"; $outBuf .= "<tr>"; $outBuf .= "<th {$noUploadStyle}></th>"; $outBuf .= "<th colspan=6 {$noUploadStyle}>"; $outBuf .= htmlentities($job["job"]["job_name"], ENT_QUOTES); $outBuf .= "</th>"; $outBuf .= "<th {$noUploadStyle}></th>"; $outBuf .= "</tr>"; } /* Job data */ $outBuf .= "<tr>"; $outBuf .= "<th {$jobStyle}>"; $outBuf .= _("Job/Dependency"); $outBuf .= "</th>"; $outBuf .= "<th {$jobStyle}>"; $outBuf .= _("Status"); $outBuf .= "</th>"; $outBuf .= "<th colspan=3 {$jobStyle}>"; $outBuf .= htmlentities($job["job"]["job_name"], ENT_QUOTES); $outBuf .= "</th>"; $outBuf .= "<th {$jobStyle}>"; $outBuf .= _("Average items/sec"); $outBuf .= "</th>"; $outBuf .= "<th {$jobStyle}>"; $outBuf .= _("ETA"); $outBuf .= "</th>"; $outBuf .= "<th {$jobStyle}>"; $outBuf .= "</th></tr>"; /* Job queue */ foreach ($job['jobqueue'] as $jq_pk => $jobqueueRec) { $varJobQueueRow = array('jqId' => $jq_pk, 'jobId' => $jobqueueRec['jq_job_fk'], 'class' => $this->getClass($jobqueueRec), 'uriFull' => $uriFull, 'depends' => $jobqueueRec['jdep_jq_depends_fk'] ? $jobqueueRec['depends'] : array(), 'status' => $jobqueueRec['jq_endtext'], 'agentName' => $jobqueueRec['jq_type'], 'itemsProcessed' => $jobqueueRec['jq_itemsprocessed'], 'startTime' => substr($jobqueueRec['jq_starttime'], 0, 16), 'endTime' => empty($jobqueueRec["jq_endtime"]) ? '' : substr($jobqueueRec['jq_endtime'], 0, 16), 'endText' => $jobqueueRec['jq_endtext']); if (!empty($jobqueueRec["jq_endtime"])) { $numSecs = strtotime($jobqueueRec['jq_endtime']) - strtotime($jobqueueRec['jq_starttime']); } else { $numSecs = time() - strtotime($jobqueueRec['jq_starttime']); } $itemsPerSec = null; if ($jobqueueRec['jq_starttime']) { $itemsPerSec = $this->showJobsDao->getNumItemsPerSec($jobqueueRec['jq_itemsprocessed'], $numSecs); $varJobQueueRow['itemsPerSec'] = $itemsPerSec; } if (empty($jobqueueRec['jq_endtime'])) { $varJobQueueRow['eta'] = $this->showJobsDao->getEstimatedTime($jobId, $jobqueueRec['jq_type'], $itemsPerSec, $job['job']['job_upload_fk']); } $varJobQueueRow['canDoActions'] = $_SESSION[Auth::USER_LEVEL] == PLUGIN_DB_ADMIN || Auth::getUserId() == $job['job']['job_user_fk']; $varJobQueueRow['isInProgress'] = $jobqueueRec['jq_end_bits'] == 0; $varJobQueueRow['isReady'] = $jobqueueRec['jq_end_bits'] == 1; switch ($jobqueueRec['jq_type']) { case 'readmeoss': $varJobQueueRow['download'] = "ReadMeOss"; break; case 'spdx2': $varJobQueueRow['download'] = "SPDX2 report"; break; case 'spdx2tv': $varJobQueueRow['download'] = "SPDX2 tag/value report"; break; case 'dep5': $varJobQueueRow['download'] = "DEP5 copyright file"; break; default: $varJobQueueRow['download'] = ""; } $outBuf .= $this->renderString('ui-showjobs-jobqueue-row.html.twig', $varJobQueueRow); } } if ($numJobs > $this->maxUploadsPerPage) { $pagination = "<p>" . MenuEndlessPage($page, $next, $uriFullMenu); } return array('showJobsData' => $outBuf, 'pagination' => $pagination); }
/** * @brief Process the upload request. */ protected function handleUpload(Request $request) { global $MODDIR; global $SYSCONFDIR; define("UPLOAD_ERR_EMPTY", 5); define("UPLOAD_ERR_INVALID_FOLDER_PK", 100); define("UPLOAD_ERR_RESEND", 200); $uploadErrors = array(UPLOAD_ERR_OK => _("No errors."), UPLOAD_ERR_INI_SIZE => _("Larger than upload_max_filesize ") . ini_get('upload_max_filesize'), UPLOAD_ERR_FORM_SIZE => _("Larger than form MAX_FILE_SIZE."), UPLOAD_ERR_PARTIAL => _("Partial upload."), UPLOAD_ERR_NO_FILE => _("No file selected."), UPLOAD_ERR_NO_TMP_DIR => _("No temporary directory."), UPLOAD_ERR_CANT_WRITE => _("Can't write to disk."), UPLOAD_ERR_EXTENSION => _("File upload stopped by extension."), UPLOAD_ERR_EMPTY => _("File is empty or you don't have permission to read the file."), UPLOAD_ERR_INVALID_FOLDER_PK => _("Invalid Folder."), UPLOAD_ERR_RESEND => _("This seems to be a resent file.")); $folderId = intval($request->get(self::FOLDER_PARAMETER_NAME)); $description = stripslashes($request->get(self::DESCRIPTION_INPUT_NAME)); $description = $this->basicShEscaping($description); $uploadedFile = $request->files->get(self::FILE_INPUT_NAME); if ($uploadedFile === null) { return array(false, $uploadErrors[UPLOAD_ERR_NO_FILE], $description); } if ($request->getSession()->get(self::UPLOAD_FORM_BUILD_PARAMETER_NAME) != $request->get(self::UPLOAD_FORM_BUILD_PARAMETER_NAME)) { return array(false, $uploadErrors[UPLOAD_ERR_RESEND], $description); } if ($uploadedFile->getSize() == 0 && $uploadedFile->getError() == 0) { return array(false, $uploadErrors[UPLOAD_ERR_EMPTY], $description); } else { if ($uploadedFile->getSize() >= UploadedFile::getMaxFilesize()) { return array(false, $uploadErrors[UPLOAD_ERR_INI_SIZE] . _(" is really ") . $uploadedFile->getSize() . " bytes.", $description); } } if (empty($folderId)) { return array(false, $uploadErrors[UPLOAD_ERR_INVALID_FOLDER_PK], $description); } if (!$uploadedFile->isValid()) { return array(false, $uploadedFile->getErrorMessage(), $description); } $originalFileName = $uploadedFile->getClientOriginalName(); $originalFileName = $this->basicShEscaping($originalFileName); $public = $request->get('public'); $publicPermission = $public == self::PUBLIC_ALL ? Auth::PERM_READ : Auth::PERM_NONE; /* Create an upload record. */ $uploadMode = 1 << 3; // code for "it came from web upload" $userId = Auth::getUserId(); $groupId = Auth::getGroupId(); $uploadId = JobAddUpload($userId, $groupId, $originalFileName, $originalFileName, $description, $uploadMode, $folderId, $publicPermission); if (empty($uploadId)) { return array(false, _("Failed to insert upload record"), $description); } try { $uploadedTempFile = $uploadedFile->move($uploadedFile->getPath(), $uploadedFile->getFilename() . '-uploaded')->getPathname(); } catch (FileException $e) { return array(false, _("Could not save uploaded file"), $description); } $projectGroup = $GLOBALS['SysConf']['DIRECTORIES']['PROJECTGROUP'] ?: 'fossy'; $wgetAgentCall = "{$MODDIR}/wget_agent/agent/wget_agent -C -g {$projectGroup} -k {$uploadId} '{$uploadedTempFile}' -c '{$SYSCONFDIR}'"; $wgetOutput = array(); exec($wgetAgentCall, $wgetOutput, $wgetReturnValue); unlink($uploadedTempFile); if ($wgetReturnValue != 0) { $message = implode(' ', $wgetOutput); if (empty($message)) { $message = _("File upload failed. Error:") . $wgetReturnValue; } return array(false, $message, $description); } $message = $this->postUploadAddJobs($request, $originalFileName, $uploadId); return array(true, $message, $description); }
/** * @brief Delete a group (for constraint, see http://www.fossology.org/projects/fossology/wiki/GroupsPerms ) * @param $groupId * @throws \Exception * @return bool true on success */ function deleteGroup($groupId) { $groupArray = $this->dbManager->getSingleRow('SELECT group_pk, group_name FROM groups WHERE group_pk=$1', array($groupId), __METHOD__ . '.exists'); if ($groupArray === false) { throw new \Exception(_("Group does not exist. Not deleted.")); } $groupConstraint = $this->dbManager->getSingleRow('SELECT count(*) cnt FROM users WHERE user_name=$1', array($groupArray['group_name']), __METHOD__ . '.contraint'); if ($groupConstraint['cnt']) { throw new \Exception(_("Group must not be deleted due to name constraint.")); } if ($_SESSION[Auth::USER_LEVEL] != PLUGIN_DB_ADMIN) { $userId = Auth::getUserId(); $adminLevel = $this->dbManager->getSingleRow("SELECT count(*) cnt FROM group_user_member WHERE group_fk=\$1 and user_fk=\$2 and group_perm=1", array($groupId, $userId), __METHOD__ . '.admin_lvl'); if ($adminLevel['cnt'] < 1) { $text = _("Permission Denied."); throw new \Exception($text); } } $this->dbManager->begin(); $this->dbManager->getSingleRow("DELETE FROM perm_upload WHERE group_fk=\$1", array($groupId), __METHOD__ . '.perm_upload'); $this->dbManager->getSingleRow("DELETE FROM group_user_member WHERE group_fk=\$1", array($groupId), __METHOD__ . '.gum'); $this->dbManager->getSingleRow("UPDATE users SET new_upload_group_fk=NULL, new_upload_perm=NULL WHERE new_upload_group_fk=\$1", array($groupId), __METHOD__ . '.upload_group'); $newGroupIdStmt = '(SELECT group_fk FROM group_user_member WHERE user_fk=user_pk LIMIT 1)'; $this->dbManager->getSingleRow("UPDATE users SET group_fk={$newGroupIdStmt} WHERE group_fk=\$1", array($groupId), __METHOD__ . '.active_group'); $this->dbManager->getSingleRow("DELETE FROM groups WHERE group_pk=\$1", array($groupId), __METHOD__ . '.delete'); $this->dbManager->commit(); return true; }
/** * \brief Delete a group. * \param $group_pk * Returns NULL on success, string on failure. */ function DeleteGroup($group_pk) { global $PG_CONN; $user_pk = Auth::getUserId(); /* Make sure groupname looks valid */ if (empty($group_pk)) { $text = _("Error: Group name must be specified."); return $text; } /* See if the group already exists */ $sql = "SELECT group_pk FROM groups WHERE group_pk = '{$group_pk}'"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); if (pg_num_rows($result) < 1) { pg_free_result($result); $text = _("Group does not exist. Not deleted."); return $text; } pg_free_result($result); /* Make sure the user has permission to delete this group * Look through all the group users (table group_user_member) * and make sure the user has admin access. */ if ($_SESSION[Auth::USER_LEVEL] != PLUGIN_DB_ADMIN) { $sql = "SELECT * FROM group_user_member WHERE group_fk = '{$group_pk}' and user_fk='{$user_pk}' and group_perm=1"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); if (pg_num_rows($result) < 1) { pg_free_result($result); $text = _("Permission Denied."); return $text; } pg_free_result($result); } /* Start transaction */ $sql = "begin"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); pg_free_result($result); /* Delete group records from perm_upload */ $sql = "delete from perm_upload where group_fk='{$group_pk}'"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); pg_free_result($result); /* Delete group records from group_user_member */ $sql = "delete from group_user_member where group_fk='{$group_pk}'"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); pg_free_result($result); /* Update new_upload_group_fk and new_upload_perm in users table */ $sql = "update users set new_upload_group_fk=NULL, new_upload_perm=NULL where new_upload_group_fk='{$group_pk}'"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); pg_free_result($result); /* Delete group records from groups table */ $sql = "delete from groups where group_pk='{$group_pk}'"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); pg_free_result($result); /* End transaction */ $sql = "commit"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); pg_free_result($result); return NULL; }
public function Output() { $groupId = Auth::getGroupId(); $rootFolder = $this->folderDao->getRootFolder(Auth::getUserId()); $folderStructure = $this->folderDao->getFolderStructure($rootFolder->getId()); $V = ""; $folder_pk = GetParm('folder', PARM_INTEGER); if (empty($folder_pk)) { $folder_pk = $rootFolder->getId(); } $NewName = GetArrayVal("newname", $_POST); $NewDesc = GetArrayVal("newdesc", $_POST); $upload_pk = GetArrayVal("upload_pk", $_POST); if (empty($upload_pk)) { $upload_pk = GetParm('upload', PARM_INTEGER); } /* Check Upload permission */ if (!empty($upload_pk) && !$this->uploadDao->isEditable($upload_pk, $groupId)) { $text = _("Permission Denied"); return "<h2>{$text}</h2>"; } $rc = $this->UpdateUploadProperties($upload_pk, $NewName, $NewDesc); if ($rc == 0) { $text = _("Nothing to Change"); $this->vars['message'] = $text; } else { if ($rc == 1) { $text = _("Upload Properties successfully changed"); $this->vars['message'] = $text; } } $this->vars['folderStructure'] = $folderStructure; $this->vars['folderId'] = $folder_pk; $this->vars['baseUri'] = $Uri = Traceback_uri() . "?mod=" . $this->Name . "&folder="; $folderUploads = $this->folderDao->getFolderUploads($folder_pk, $groupId); $uploadsById = array(); /* @var $uploadProgress UploadProgress */ foreach ($folderUploads as $uploadProgress) { if ($uploadProgress->getGroupId() != $groupId) { continue; } if (!$this->uploadDao->isEditable($uploadProgress->getId(), $groupId)) { continue; } $display = $uploadProgress->getFilename() . _(" from ") . date("Y-m-d H:i", $uploadProgress->getTimestamp()); $uploadsById[$uploadProgress->getId()] = $display; } $this->vars['uploadList'] = $uploadsById; if (empty($upload_pk)) { reset($uploadsById); $upload_pk = key($uploadsById); } $this->vars['uploadId'] = $upload_pk; if ($upload_pk) { $upload = $this->uploadDao->getUpload($upload_pk); if (empty($upload)) { $this->vars['message'] = _("Missing upload."); return 0; } } else { $upload = null; } $baseFolderUri = $this->vars['baseUri'] . "{$folder_pk}&upload="; $this->vars['uploadAction'] = "onchange=\"js_url(this.value, '{$baseFolderUri}')\""; $this->vars['uploadFilename'] = $upload ? $upload->getFilename() : ''; $this->vars['uploadDesc'] = $upload ? $upload->getDescription() : ''; $this->vars['content'] = $V; return $this->render('admin_upload_edit.html.twig'); }
/** * @brief Find all of my jobs submitted within the last n hours. * * @param $allusers * * @return array of job_pk's **/ public function myJobs($allusers) { $jobArray = array(); $allusers_str = $allusers == 0 ? "job_user_fk='" . Auth::getUserId() . "' and " : ($allusers_str = ""); $statementName = __METHOD__ . "{$allusers_str}"; $this->dbManager->prepare($statementName, "SELECT job_pk, job_upload_fk FROM job WHERE {$allusers_str} job_queued >= (now() - interval '" . $this->nhours . " hours') ORDER BY job_queued DESC"); $result = $this->dbManager->execute($statementName); while ($row = $this->dbManager->fetchArray($result)) { if (!empty($row['job_upload_fk'])) { $uploadIsAccessible = $this->uploadDao->isAccessible($row['job_upload_fk'], Auth::getGroupId()); if (!$uploadIsAccessible) { continue; } } $jobArray[] = $row['job_pk']; } $this->dbManager->freeResult($result); return $jobArray; }
/** * \brief Generate the text for this plugin. */ public function Output() { global $PG_CONN; $V = ""; /* If this is a POST, then process the request. */ $User = GetParm('userid', PARM_TEXT); $Confirm = GetParm('confirm', PARM_INTEGER); if (!empty($User)) { if ($Confirm != 1) { $rc = "Deletion not confirmed. Not deleted."; } else { $rc = $this->Delete($User); } if (empty($rc)) { /* Need to refresh the screen */ $text = _("User deleted."); $this->vars['message'] = $text; } else { $this->vars['message'] = $rc; } } /* Get the user list */ $currentUserId = Auth::getUserId(); $sql = "SELECT user_pk,user_name,user_desc FROM users WHERE user_pk != '{$currentUserId}' AND user_pk != '1' ORDER BY user_name"; $result = pg_query($PG_CONN, $sql); DBCheckResult($result, $sql, __FILE__, __LINE__); if (pg_num_rows($result) == 0) { $V .= _("No users to delete."); } else { /* Build HTML form */ $V .= _("Deleting a user removes the user entry from the FOSSology system. The user's name, account information, and password will be <font color='red'>permanently</font> removed. (There is no 'undo' to this delete.)<P />\n"); $V .= "<form name='formy' method='POST'>\n"; // no url = this url $V .= _("To delete a user, enter the following information:<P />\n"); $Style = "<tr><td colspan=3 style='background:black;'></td></tr><tr>"; $Val = htmlentities(GetParm('userid', PARM_TEXT), ENT_QUOTES); $V .= "<ol>\n"; $V .= _("<li>Select the user to delete.<br />"); $V .= "<select name='userid'>\n"; while ($row = pg_fetch_assoc($result)) { $V .= "<option value='" . $row['user_pk'] . "'>"; $V .= $row['user_name']; $V .= "</option>\n"; } $V .= "</select>\n"; $text = _("Confirm user deletion"); $V .= "<P /><li>{$text}: <input type='checkbox' name='confirm' value='1'>"; $V .= "</ol>\n"; $text = _("Delete"); $V .= "<input type='submit' value='{$text}!'>\n"; $V .= "</form>\n"; } pg_free_result($result); return $V; }
/** * @brief Process the upload request. */ protected function handleUpload(Request $request) { global $MODDIR; global $SYSCONFDIR; global $Plugins; $folderId = intval($request->get(self::FOLDER_PARAMETER_NAME)); $description = stripslashes($request->get(self::DESCRIPTION_INPUT_NAME)); $description = $this->basicShEscaping($description); $getUrlThatMightIncludeSpaces = trim($request->get(self::GETURL_PARAM)); $getUrl = str_replace(" ", "%20", $getUrlThatMightIncludeSpaces); if (empty($getUrl)) { return array(false, _("Empty URL") . $getUrl, $description); } if (preg_match("@^((http)|(https))://([[:alnum:]]+)@i", $getUrl) != 1) { return array(false, _("Invalid URL") . $getUrl, $description); } $getUrl = $this->basicShEscaping($getUrl); if ($request->getSession()->get(self::UPLOAD_FORM_BUILD_PARAMETER_NAME) != $request->get(self::UPLOAD_FORM_BUILD_PARAMETER_NAME)) { $text = _("This seems to be a resent file."); return array(false, $text, $description); } if (empty($folderId)) { $text = _("Invalid Folder."); return array(false, $text, $description); } $public = $request->get('public'); $publicPermission = $public == self::PUBLIC_ALL ? Auth::PERM_READ : Auth::PERM_NONE; $Name = trim($request->get('name')); if (empty($Name)) { $Name = basename($getUrl); } $ShortName = basename($Name); if (empty($ShortName)) { $ShortName = $Name; } /* Create an upload record. */ $uploadMode = 1 << 2; // code for "it came from wget" $userId = Auth::getUserId(); $groupId = Auth::getGroupId(); $uploadId = JobAddUpload($userId, $groupId, $ShortName, $getUrl, $description, $uploadMode, $folderId, $publicPermission); if (empty($uploadId)) { $text = _("Failed to insert upload record"); return array(false, $text, $description); } /* Create the job: job "wget" */ $jobpk = JobAddJob($userId, $groupId, "wget", $uploadId); if (empty($jobpk) || $jobpk < 0) { $text = _("Failed to insert job record"); return array(false, $text, $description); } $VCSType = trim($request->get('vcstype')); $VCSType = $this->basicShEscaping($VCSType); $jq_args = "{$uploadId} - {$getUrl} {$VCSType} "; $Username = trim($request->get('username')); $Username = $this->basicShEscaping($Username); if (!empty($Username)) { $jq_args .= "--username {$Username} "; } $Passwd = trim($request->get('passwd')); $Passwd = $this->basicShEscaping($Passwd); if (!empty($Passwd)) { $jq_args .= "--password {$Passwd}"; } $jobqueuepk = JobQueueAdd($jobpk, "wget_agent", $jq_args, NULL, NULL); if (empty($jobqueuepk)) { $text = _("Failed to insert task 'wget_agent' into job queue"); return array(false, $text, $description); } /* schedule agents */ $unpackplugin =& $Plugins[plugin_find_id("agent_unpack")]; $ununpack_jq_pk = $unpackplugin->AgentAdd($jobpk, $uploadId, $ErrorMsg, array("wget_agent")); if ($ununpack_jq_pk < 0) { return array(false, _($ErrorMsg), $description); } $adj2nestplugin =& $Plugins[plugin_find_id("agent_adj2nest")]; $adj2nest_jq_pk = $adj2nestplugin->AgentAdd($jobpk, $uploadId, $ErrorMsg, array()); if ($adj2nest_jq_pk < 0) { return array(false, _($ErrorMsg), $description); } AgentCheckBoxDo($jobpk, $uploadId); $msg = ""; /** check if the scheudler is running */ $status = GetRunnableJobList(); if (empty($status)) { $msg .= _("Is the scheduler running? "); } $Url = Traceback_uri() . "?mod=showjobs&upload={$uploadId}"; $text = _("The upload"); $text1 = _("has been queued. It is"); $msg .= "{$text} {$Name} {$text1} "; $keep = "<a href='{$Url}'>upload #" . $uploadId . "</a>.\n"; return array(true, $msg . $keep, $description); }
/** * @brief extends standard Output to handle empty uploads */ function Output() { if ($this->invalidParm) { $this->vars['content'] = 'This upload contains no files!<br><a href="' . Traceback_uri() . '?mod=browse">Go back to browse view</a>'; return $this->render("include/base.html.twig"); } $uploadId = GetParm("upload", PARM_INTEGER); if (empty($uploadId)) { return new Response("", Response::HTTP_BAD_REQUEST); } $uploadTreeId = GetParm("item", PARM_INTEGER); if (empty($uploadTreeId)) { return new Response("", Response::HTTP_BAD_REQUEST); } $userId = Auth::getUserId(); $groupId = Auth::getGroupId(); $lastItem = GetParm("lastItem", PARM_INTEGER); if (!empty($lastItem)) { $this->updateLastItem($userId, $groupId, $lastItem); } $uploadTreeTableName = $this->uploadDao->getUploadtreeTableName($uploadId); $itemTreeBounds = $this->uploadDao->getItemTreeBounds($uploadTreeId, $uploadTreeTableName); $this->vars['micromenu'] = Dir2Browse('license', $uploadTreeId, NULL, $showBox = 0, "View", -1, '', '', $uploadTreeTableName); global $Plugins; /** @var ui_view $view */ $view =& $Plugins[plugin_find_id("view")]; $licenseId = GetParm("licenseId", PARM_INTEGER); $selectedAgentId = GetParm("agentId", PARM_INTEGER); $highlightId = GetParm("highlightId", PARM_INTEGER); $clearingId = GetParm("clearingId", PARM_INTEGER); if ($clearingId !== null) { $highlightId = -1; } else { if ($highlightId !== null) { $clearingId = -1; } } $baseUri = Traceback_uri(); $this->vars['baseuri'] = $baseUri; $this->vars['uri'] = $baseUri . "?mod=" . $this->Name . Traceback_parm_keep(array('upload', 'folder')); $this->vars['bulkHistoryHighlightUri'] = $this->vars['uri']; $this->vars['optionName'] = "skipFile"; $this->vars['formName'] = "uiClearingForm"; $this->vars['ajaxAction'] = "setNextPrev"; $highlights = $this->getSelectedHighlighting($itemTreeBounds, $licenseId, $selectedAgentId, $highlightId, $clearingId, $uploadId); $isSingleFile = !$itemTreeBounds->containsFiles(); $hasWritePermission = $this->uploadDao->isEditable($uploadId, $groupId); $clearingDecisions = null; if ($isSingleFile || $hasWritePermission) { $clearingDecisions = $this->clearingDao->getFileClearings($itemTreeBounds, $groupId, false); } if ($isSingleFile && $hasWritePermission) { $this->vars['bulkUri'] = Traceback_uri() . "?mod=popup-license"; $licenseArray = $this->licenseDao->getLicenseArray($groupId); // $clearingDecision = $this->clearingDao->getRelevantClearingDecision($itemTreeBounds, $groupId); list($addedResults, $removedResults) = $this->clearingDecisionEventProcessor->getCurrentClearings($itemTreeBounds, $groupId, LicenseMap::CONCLUSION); if (count($addedResults) + count($removedResults) > 0) { array_unshift($licenseArray, array('id' => 0, 'fullname' => '', 'shortname' => '------')); } /** @var ClearingResult $result */ foreach ($removedResults as $result) { array_unshift($licenseArray, array('id' => $result->getLicenseId(), 'fullname' => $result->getLicenseFullName(), 'shortname' => $result->getLicenseShortName())); } /** @var ClearingResult $result */ foreach ($addedResults as $result) { array_unshift($licenseArray, array('id' => $result->getLicenseId(), 'fullname' => $result->getLicenseFullName(), 'shortname' => $result->getLicenseShortName())); } $this->vars['licenseArray'] = $licenseArray; } elseif ($isSingleFile) { $this->vars['auditDenied'] = true; } $clearingHistory = array(); $selectedClearingType = false; if ($hasWritePermission) { $clearingHistory = $this->getClearingHistory($clearingDecisions); } if (count($clearingHistory) > 0) { $selectedClearingType = $this->decisionTypes->getTypeByName($clearingHistory[0]['type']); } $bulkHistory = $this->clearingDao->getBulkHistory($itemTreeBounds, $groupId); $ModBack = GetParm("modback", PARM_STRING) ?: "license"; list($pageMenu, $textView) = $view->getView(NULL, $ModBack, 0, "", $highlights, false, true); $this->vars['uploadId'] = $uploadId; $this->vars['itemId'] = $uploadTreeId; $this->vars['pageMenu'] = $pageMenu; $this->vars['textView'] = $textView; $this->vars['legendData'] = $this->highlightRenderer->getLegendData($selectedAgentId || $clearingId); $this->vars['clearingTypes'] = $this->decisionTypes->getMap(); $this->vars['selectedClearingType'] = $selectedClearingType; $this->vars['tmpClearingType'] = $this->clearingDao->isDecisionWip($uploadTreeId, $groupId); $this->vars['clearingHistory'] = $clearingHistory; $this->vars['bulkHistory'] = $bulkHistory; $noLicenseUploadTreeView = new UploadTreeProxy($uploadId, $options = array(UploadTreeProxy::OPT_SKIP_THESE => "noLicense", UploadTreeProxy::OPT_GROUP_ID => $groupId), $uploadTreeTableName, $viewName = 'no_license_uploadtree' . $uploadId); $filesOfInterest = $noLicenseUploadTreeView->count(); $nonClearedUploadTreeView = new UploadTreeProxy($uploadId, $options = array(UploadTreeProxy::OPT_SKIP_THESE => "alreadyCleared", UploadTreeProxy::OPT_GROUP_ID => $groupId), $uploadTreeTableName, $viewName = 'already_cleared_uploadtree' . $uploadId); $filesToBeCleared = $nonClearedUploadTreeView->count(); $filesAlreadyCleared = $filesOfInterest - $filesToBeCleared; $this->vars['message'] = _("Cleared") . ": {$filesAlreadyCleared}/{$filesOfInterest}"; return $this->render("ui-clearing-view.html.twig"); }