Exemplo n.º 1
0
 /**
  * \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");
 }
Exemplo n.º 2
0
 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);
 }
Exemplo n.º 3
0
 /**
  * \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, $userId)
 {
     /* 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" */
     $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;
 }
Exemplo n.º 4
0
 /**
  * \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;
 }
Exemplo n.º 5
0
 /**
  * @param int $jobId
  * @param int $uploadId
  * @param string $errorMsg
  * @param Request $request
  */
 public function scheduleAgent($jobId, $uploadId, &$errorMsg, $request)
 {
     $reuseUploadPair = explode(',', $request->get(self::UPLOAD_TO_REUSE_SELECTOR_NAME), 2);
     if (count($reuseUploadPair) == 2) {
         list($reuseUploadId, $reuseGroupId) = $reuseUploadPair;
     } else {
         $errorMsg .= 'no reuse upload id given';
         return -1;
     }
     $groupId = $request->get('groupId', Auth::getGroupId());
     $reuseModeVal = $request->get('reuseMode');
     $reuseMode = empty($reuseModeVal) ? 0 : 1;
     $this->createPackageLink($uploadId, $reuseUploadId, $groupId, $reuseGroupId, $reuseMode);
     return $this->doAgentAdd($jobId, $uploadId, $errorMsg, array("agent_adj2nest"), $uploadId);
 }
Exemplo n.º 6
0
 /**
  * 
  * @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;
 }
Exemplo n.º 7
0
 /**
  * @return array
  */
 public function getUserChoices($groupId = null)
 {
     if (empty($groupId)) {
         $groupId = Auth::getGroupId();
     }
     $userChoices = array();
     $statementN = __METHOD__;
     $sql = "SELECT user_pk, user_name FROM users LEFT JOIN group_user_member AS gum ON users.user_pk = gum.user_fk" . " WHERE gum.group_fk = \$1";
     $this->dbManager->prepare($statementN, $sql);
     $res = $this->dbManager->execute($statementN, array($groupId));
     while ($rw = $this->dbManager->fetchArray($res)) {
         $userChoices[$rw['user_pk']] = $rw['user_name'];
     }
     $this->dbManager->freeResult($res);
     return $userChoices;
 }
Exemplo n.º 8
0
 protected function handle(Request $request)
 {
     $groupId = Auth::getGroupId();
     $uploadIds = $request->get('uploads') ?: array();
     $uploadIds[] = intval($request->get('upload'));
     $addUploads = array();
     foreach ($uploadIds as $uploadId) {
         if (empty($uploadId)) {
             continue;
         }
         try {
             $addUploads[$uploadId] = $this->getUpload($uploadId, $groupId);
         } catch (Exception $e) {
             return $this->flushContent($e->getMessage());
         }
     }
     $folderId = $request->get('folder');
     if (!empty($folderId)) {
         /* @var $folderDao FolderDao */
         $folderDao = $this->getObject('dao.folder');
         $folderUploads = $folderDao->getFolderUploads($folderId, $groupId);
         foreach ($folderUploads as $uploadProgress) {
             $addUploads[$uploadProgress->getId()] = $uploadProgress;
         }
     }
     if (empty($addUploads)) {
         return $this->flushContent(_('No upload selected'));
     }
     $upload = array_pop($addUploads);
     try {
         list($jobId, $jobQueueId) = $this->getJobAndJobqueue($groupId, $upload, $addUploads);
     } catch (Exception $ex) {
         return $this->flushContent($ex->getMessage());
     }
     $vars = array('jqPk' => $jobQueueId, 'downloadLink' => Traceback_uri() . "?mod=download&report=" . $jobId, 'reportType' => $this->outputFormat);
     $text = sprintf(_("Generating " . $this->outputFormat . " report for '%s'"), $upload->getFilename());
     $vars['content'] = "<h2>" . $text . "</h2>";
     $content = $this->renderer->loadTemplate("report.html.twig")->render($vars);
     $message = '<h3 id="jobResult"></h3>';
     $request->duplicate(array('injectedMessage' => $message, 'injectedFoot' => $content, 'mod' => 'showjobs'))->overrideGlobals();
     $showJobsPlugin = \plugin_find('showjobs');
     $showJobsPlugin->OutputOpen();
     return $showJobsPlugin->getResponse();
 }
Exemplo n.º 9
0
 /**
  * \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'));
 }
Exemplo n.º 10
0
 protected function handle(Request $request)
 {
     $folderId = intval($request->get('folder'));
     /* @var $folderDao FolderDao */
     $folderDao = $this->getObject('dao.folder');
     $results = array();
     $childFolders = $folderDao->getFolderChildFolders($folderId);
     foreach ($childFolders as $folder) {
         $results[$folder['foldercontents_pk']] = '/' . $folder['folder_name'];
     }
     $childUploads = $folderDao->getFolderChildUploads($folderId, Auth::getGroupId());
     foreach ($childUploads as $upload) {
         $results[$upload['foldercontents_pk']] = $upload['upload_filename'];
     }
     if (!$request->get('removable')) {
         return new JsonResponse($results);
     }
     $filterResults = array();
     foreach ($folderDao->getRemovableContents($folderId) as $content) {
         $filterResults[$content] = $results[$content];
     }
     return new JsonResponse($filterResults);
 }
Exemplo n.º 11
0
 /**
  * @param Request $request
  * @return Response
  */
 protected function handle(Request $request)
 {
     $upload = intval($request->get("upload"));
     $groupId = Auth::getGroupId();
     if (!$this->uploadDao->isAccessible($upload, $groupId)) {
         throw new \Exception("Permission Denied");
     }
     $item = intval($request->get("item"));
     $this->uploadtree_tablename = $this->uploadDao->getUploadtreeTableName($upload);
     $itemTreeBounds = $this->uploadDao->getItemTreeBounds($item, $this->uploadtree_tablename);
     $left = $itemTreeBounds->getLeft();
     if (empty($left)) {
         throw new \Exception("Job unpack/adj2nest hasn't completed.");
     }
     $scannerAgents = array_keys($this->agentNames);
     $scanJobProxy = new ScanJobProxy($this->agentDao, $upload);
     $scanJobProxy->createAgentStatus($scannerAgents);
     $selectedAgentId = intval($request->get('agentId'));
     $tag_pk = intval($request->get('tag'));
     $UniqueTagArray = array();
     $this->licenseProjector = new LicenseMap($this->getObject('db.manager'), $groupId, LicenseMap::CONCLUSION, true);
     $vars = $this->createFileListing($tag_pk, $itemTreeBounds, $UniqueTagArray, $selectedAgentId, $groupId, $scanJobProxy);
     return new JsonResponse(array('sEcho' => intval($request->get('sEcho')), 'aaData' => $vars['fileData'], 'iTotalRecords' => intval($request->get('totalRecords')), 'iTotalDisplayRecords' => $vars['iTotalDisplayRecords']));
 }
 /**
  * @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);
 }
Exemplo n.º 13
0
 /**
  * \brief Generate the view contents in HTML
  *
  * @param resource $inputFile
  * @param string $BackMod
  * @param int $ShowMenu
  * @param int $ShowHeader
  * @param null $ShowText
  * @param bool $ViewOnly
  * @param bool $DispView
  * @param Highlight[] $highlightEntries
  * @param bool $insertBacklink
  *
  * \note This function is intended to be called from other plugins.
  */
 function getView($inputFile = NULL, $BackMod = "browse", $ShowHeader = 1, $ShowText = NULL, $highlightEntries = array(), $insertBacklink = false, $getPageMenuInline = false)
 {
     if ($this->State != PLUGIN_STATE_READY) {
         $output = "Invalid plugin state: " . $this->State;
         return $getPageMenuInline ? array("Error", $output) : $output;
     }
     $Upload = GetParm("upload", PARM_INTEGER);
     if (!empty($Upload) && !$this->uploadDao->isAccessible($Upload, Auth::getGroupId())) {
         $output = "Access denied";
         return $getPageMenuInline ? array("Error", $output) : $output;
     }
     $Item = GetParm("item", PARM_INTEGER);
     $Page = GetParm("page", PARM_INTEGER);
     $licenseId = GetParm("licenseId", PARM_INTEGER);
     if (!$inputFile && empty($Item)) {
         $output = "invalid input file";
         return $getPageMenuInline ? array("Error", $output) : $output;
     }
     $uploadtree_tablename = $this->uploadDao->getUploadtreeTableName($Upload);
     if ($ShowHeader) {
         $Uri = Traceback_uri() . "?mod=browse" . Traceback_parm_keep(array('item', 'show', 'folder', 'upload'));
         /* No item */
         $header = Dir2Browse($BackMod, $Item, NULL, $showBox = 0, "View", -1, '', '', $uploadtree_tablename);
         $this->vars['micromenu'] = $header;
     }
     /* Display file contents */
     $output = "";
     $openedFin = False;
     $Format = $this->microMenu->getFormatParameter($Item);
     if (empty($inputFile)) {
         $inputFile = @fopen(RepPathItem($Item), "rb");
         if ($inputFile) {
             $openedFin = true;
         }
         if (empty($inputFile)) {
             $output = $this->outputWhenFileNotInRepo($Upload, $Item);
             return $getPageMenuInline ? array("Error", $output) : $output;
         }
     }
     rewind($inputFile);
     $Uri = preg_replace('/&page=[0-9]*/', '', Traceback());
     $blockSize = $Format == 'hex' ? $this->blockSizeHex : $this->blockSizeText;
     if (!isset($Page) && !empty($licenseId)) {
         $startPos = -1;
         foreach ($highlightEntries as $highlightEntry) {
             if ($highlightEntry->getLicenseId() == $licenseId && ($startPos == -1 || $startPos > $highlightEntry->getStart())) {
                 $startPos = $highlightEntry->getStart();
             }
         }
         if ($startPos != -1) {
             $Page = floor($startPos / $blockSize);
         }
     }
     if (!empty($ShowText)) {
         echo $ShowText, "<hr>";
     }
     $PageMenu = $this->GetFileJumpMenu($inputFile, $Page, $blockSize, $Uri);
     $PageSize = $blockSize * $Page;
     if (!empty($PageMenu) and !$getPageMenuInline) {
         $output .= "<center>{$PageMenu}</center><br>\n";
     }
     $startAt = $PageSize;
     $endAt = $PageSize + $blockSize;
     $relevantHighlightEntries = array();
     foreach ($highlightEntries as $highlightEntry) {
         if ($highlightEntry->getStart() < $endAt && $highlightEntry->getEnd() >= $startAt) {
             $relevantHighlightEntries[] = $highlightEntry;
         }
     }
     $this->highlightProcessor->sortHighlights($relevantHighlightEntries);
     $splitPositions = $this->highlightProcessor->calculateSplitPositions($relevantHighlightEntries);
     if ($Format == 'hex') {
         $output .= $this->getHex($inputFile, $PageSize, $this->blockSizeHex, $splitPositions);
     } else {
         $output .= $this->getText($inputFile, $PageSize, $Format == 'text' ? 0 : 1, $this->blockSizeText, $splitPositions, $insertBacklink);
     }
     if (!empty($PageMenu) and !$getPageMenuInline) {
         $output .= "<P /><center>{$PageMenu}</center><br>\n";
     }
     if ($openedFin) {
         fclose($inputFile);
     }
     return $getPageMenuInline ? array($PageMenu, $output) : $output;
 }
Exemplo n.º 14
0
 public function Output()
 {
     $OutBuf = "";
     $uploadId = GetParm("upload", PARM_INTEGER);
     $item = GetParm("item", PARM_INTEGER);
     $filter = GetParm("filter", PARM_STRING);
     /* check upload permissions */
     if (!$this->uploadDao->isAccessible($uploadId, Auth::getGroupId())) {
         $text = _("Permission Denied");
         return "<h2>{$text}</h2>";
     }
     /* Get uploadtree_tablename */
     $uploadtree_tablename = GetUploadtreeTableName($uploadId);
     $this->uploadtree_tablename = $uploadtree_tablename;
     /************************/
     /* Show the folder path */
     /************************/
     $this->vars['dir2browse'] = Dir2Browse($this->Name, $item, NULL, 1, "Browse", -1, '', '', $uploadtree_tablename);
     if (empty($uploadId)) {
         return 'no item selected';
     }
     /** advanced interface allowing user to select dataset (agent version) */
     $dataset = $this->agentName . "_dataset";
     $arstable = $this->agentName . "_ars";
     /** get proper agent_id */
     $agentId = GetParm("agent", PARM_INTEGER);
     if (empty($agentId)) {
         $agentId = LatestAgentpk($uploadId, $arstable);
     }
     if ($agentId == 0) {
         /** schedule copyright */
         $OutBuf .= ActiveHTTPscript("Schedule");
         $OutBuf .= "<script language='javascript'>\n";
         $OutBuf .= "function Schedule_Reply()\n";
         $OutBuf .= "  {\n";
         $OutBuf .= "  if ((Schedule.readyState==4) && (Schedule.status==200 || Schedule.status==400))\n";
         $OutBuf .= "    document.getElementById('msgdiv').innerHTML = Schedule.responseText;\n";
         $OutBuf .= "  }\n";
         $OutBuf .= "</script>\n";
         $OutBuf .= "<form name='formy' method='post'>\n";
         $OutBuf .= "<div id='msgdiv'>\n";
         $OutBuf .= _("No data available.");
         $OutBuf .= "<input type='button' name='scheduleAgent' value='Schedule Agent'";
         $OutBuf .= "onClick=\"Schedule_Get('" . Traceback_uri() . "?mod=schedule_agent&upload={$uploadId}&agent=agent_{$this->agentName}')\">\n";
         $OutBuf .= "</input>";
         $OutBuf .= "</div> \n";
         $OutBuf .= "</form>\n";
         $this->vars['pageContent'] = $OutBuf;
         return;
     }
     $AgentSelect = AgentSelect($this->agentName, $uploadId, $dataset, $agentId, "onchange=\"addArsGo('newds', 'copyright_dataset');\"");
     /** change the copyright  result when selecting one version of copyright */
     if (!empty($AgentSelect)) {
         $action = Traceback_uri() . '?mod=' . GetParm('mod', PARM_RAW) . Traceback_parm_keep(array('upload', 'item'));
         $OutBuf .= "<script type='text/javascript'>\n        function addArsGo(formid, selectid)\n        {\n          var selectobj = document.getElementById(selectid);\n          var Agent_pk = selectobj.options[selectobj.selectedIndex].value;\n          document.getElementById(formid).action='{$action}'+'&agent='+Agent_pk;\n          document.getElementById(formid).submit();\n          return;\n        }\n      </script>";
         $OutBuf .= "<form action=\"{$action}\" id=\"newds\" method=\"POST\">{$AgentSelect}</form>";
     }
     $selectKey = $filter == 'nolic' ? 'nolic' : 'all';
     $OutBuf .= "<select name='view_filter' id='view_filter' onchange='ChangeFilter(this,{$uploadId}, {$item});'>";
     foreach (array('all' => _("Show all"), 'nolic' => _("Show files without licenses")) as $key => $text) {
         $selected = $selectKey == $key ? "selected" : "";
         $OutBuf .= "<option {$selected} value=\"{$key}\">{$text}</option>";
     }
     $OutBuf .= "</select>";
     $uri = preg_replace("/&item=([0-9]*)/", "", Traceback());
     list($tables, $tableVars) = $this->ShowUploadHist($uploadId, $item, $uri, $selectKey, $uploadtree_tablename, $agentId);
     $this->vars['tables'] = $tableVars;
     $this->vars['pageContent'] = $OutBuf . $tables;
     $this->vars['scriptBlock'] = $this->createScriptBlock();
     return;
 }
Exemplo n.º 15
0
 /**
  * @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);
 }
Exemplo n.º 16
0
 /**
  * \brief This function is called when user output is
  * requested.  This function is responsible for content.
  */
 protected function getPathAndName()
 {
     if ($this->State != \PLUGIN_STATE_READY) {
         throw new Exception('Download plugin is not ready');
     }
     global $container;
     /** @var DbManager $dbManager */
     $dbManager = $container->get('db.manager');
     if (!$dbManager->getDriver()) {
         throw new Exception("Missing database connection.");
     }
     $reportId = GetParm("report", PARM_INTEGER);
     $item = GetParm("item", PARM_INTEGER);
     $logJq = GetParm('log', PARM_INTEGER);
     if (!empty($reportId)) {
         $row = $dbManager->getSingleRow("SELECT * FROM reportgen WHERE job_fk = \$1", array($reportId), "reportFileName");
         if ($row === false) {
             throw new Exception("Missing report");
         }
         $path = $row['filepath'];
         $filename = basename($path);
         $uploadId = $row['upload_fk'];
     } elseif (!empty($logJq)) {
         $sql = "SELECT jq_log, job_upload_fk FROM jobqueue LEFT JOIN job ON job.job_pk = jobqueue.jq_job_fk WHERE jobqueue.jq_pk =\$1";
         $row = $dbManager->getSingleRow($sql, array($logJq), "jqLogFileName");
         if ($row === false) {
             throw new Exception("Missing report");
         }
         $path = $row['jq_log'];
         $filename = basename($path);
         $uploadId = $row['job_upload_fk'];
     } elseif (empty($item)) {
         throw new Exception("Invalid item parameter");
     } else {
         $path = RepPathItem($item);
         if (empty($path)) {
             throw new Exception("Invalid item parameter");
         }
         $fileHandle = @fopen(RepPathItem($item), "rb");
         /* note that CheckRestore() does not return. */
         if (empty($fileHandle)) {
             $this->CheckRestore($item, $path);
         }
         $row = $dbManager->getSingleRow("SELECT ufile_name, upload_fk FROM uploadtree WHERE uploadtree_pk = \$1", array($item));
         if ($row === false) {
             throw new Exception("Missing item");
         }
         $filename = $row['ufile_name'];
         $uploadId = $row['upload_fk'];
     }
     /* @var $uploadDao UploadDao */
     $uploadDao = $GLOBALS['container']->get('dao.upload');
     if (!Auth::isAdmin() && !$uploadDao->isAccessible($uploadId, Auth::getGroupId())) {
         throw new Exception("No Permission: {$uploadId}");
     }
     if (!file_exists($path)) {
         throw new Exception("File does not exist");
     }
     if (!is_file($path)) {
         throw new Exception("Not a regular file");
     }
     return array($path, $filename);
 }
Exemplo n.º 17
0
 public function Output()
 {
     $uploadId = GetParm("upload", PARM_INTEGER);
     if (!$this->uploadDao->isAccessible($uploadId, Auth::getGroupId())) {
         return;
     }
     $itemId = GetParm("item", PARM_INTEGER);
     $this->vars['micromenu'] = Dir2Browse("browse", $itemId, NULL, $showBox = 0, "View-Meta");
     $V = "";
     $V .= $this->ShowTagInfo($uploadId, $itemId);
     $V .= $this->ShowPackageinfo($uploadId, $itemId, 1);
     $V .= $this->ShowMetaView($uploadId, $itemId);
     $V .= $this->ShowSightings($uploadId, $itemId);
     $V .= $this->ShowView($uploadId, $itemId);
     return $V;
 }
Exemplo n.º 18
0
 protected function handle(Request $request)
 {
     $vars = array();
     $uploadId = intval($request->get('upload'));
     $uploadTreeId = intval($request->get('item'));
     if (empty($uploadTreeId) || empty($uploadId)) {
         $text = _("Empty Input");
         $vars['message'] = "<h2>{$text}</h2>";
         return $this->responseBad($vars);
     }
     if (!$this->uploadDao->isAccessible($uploadId, Auth::getGroupId())) {
         $text = _("Permission Denied");
         $vars['message'] = "<h2>{$text}</h2>";
         return $this->responseBad();
     }
     $uploadTreeTableName = $this->uploadDao->getUploadtreeTableName($uploadId);
     $uploadEntry = $this->uploadDao->getUploadEntry($uploadTreeId, $uploadTreeTableName);
     if (Isdir($uploadEntry['ufile_mode']) || Iscontainer($uploadEntry['ufile_mode'])) {
         $parent = $this->uploadDao->getUploadParent($uploadEntry['upload_fk']);
         if (!isset($parent)) {
             return $this->responseBad();
         }
         $uploadTree = $this->uploadDao->getNextItem($uploadEntry['upload_fk'], $parent);
         if ($uploadTree === UploadDao::NOT_FOUND) {
             return $this->responseBad();
         }
         $uploadTreeId = $uploadTree->getId();
         return new RedirectResponse(Traceback_uri() . '?mod=' . $this->getName() . Traceback_parm_keep(array('show', 'upload')) . "&item={$uploadTreeId}");
     }
     if (empty($uploadTreeId)) {
         return $this->responseBad('No item selected.');
     }
     $copyrightDecisionMap = $this->decisionTypes->getMap();
     $vars['micromenu'] = Dir2Browse($this->modBack, $uploadTreeId, NULL, $showBox = 0, "View", -1, '', '', $uploadTreeTableName);
     $lastItem = GetParm("lastItem", PARM_INTEGER);
     $changed = GetParm("changedSomething", PARM_STRING);
     $userId = Auth::getUserId();
     if (!empty($lastItem) && $changed == "true") {
         $lastUploadEntry = $this->uploadDao->getUploadEntry($lastItem, $uploadTreeTableName);
         $clearingType = $_POST['clearingTypes'];
         $description = $_POST['description'];
         $textFinding = $_POST['textFinding'];
         $comment = $_POST['comment'];
         $this->copyrightDao->saveDecision($this->decisionTableName, $lastUploadEntry['pfile_fk'], $userId, $clearingType, $description, $textFinding, $comment);
     }
     $scanJobProxy = new ScanJobProxy($this->agentDao, $uploadId);
     $scanJobProxy->createAgentStatus(array($this->agentName));
     $selectedScanners = $scanJobProxy->getLatestSuccessfulAgentIds();
     $highlights = array();
     if (array_key_exists($this->agentName, $selectedScanners)) {
         $latestXpAgentId = $selectedScanners[$this->agentName];
         $highlights = $this->copyrightDao->getHighlights($uploadTreeId, $this->tableName, $latestXpAgentId, $this->typeToHighlightTypeMap);
     }
     if (count($highlights) < 1) {
         $vars['message'] = _("No ") . $this->tableName . _(" data is available for this file.");
     }
     /* @var $view ui_view */
     $view = plugin_find("view");
     $theView = $view->getView(null, null, $showHeader = 0, "", $highlights, false, true);
     list($pageMenu, $textView) = $theView;
     list($description, $textFinding, $comment, $decisionType) = $this->copyrightDao->getDecision($this->decisionTableName, $uploadEntry['pfile_fk']);
     $vars['description'] = $description;
     $vars['textFinding'] = $textFinding;
     $vars['comment'] = $comment;
     $vars['itemId'] = $uploadTreeId;
     $vars['uploadId'] = $uploadId;
     $vars['pageMenu'] = $pageMenu;
     $vars['textView'] = $textView;
     $vars['legendBox'] = $this->legendBox();
     $vars['uri'] = Traceback_uri() . "?mod=" . $this->Name;
     $vars['optionName'] = $this->optionName;
     $vars['formName'] = "CopyRightForm";
     $vars['ajaxAction'] = $this->ajaxAction;
     $vars['skipOption'] = $this->skipOption;
     $vars['selectedClearingType'] = $decisionType;
     $vars['clearingTypes'] = $copyrightDecisionMap;
     $vars['xptext'] = $this->xptext;
     $agentId = intval($request->get("agent"));
     $vars = array_merge($vars, $this->additionalVars($uploadId, $uploadTreeId, $agentId));
     return $this->render('ui-cp-view.html.twig', $this->mergeWithDefault($vars));
 }
Exemplo n.º 19
0
 /**
  * \brief This function returns the scheduler status.
  */
 function Output()
 {
     global $PG_CONN;
     global $SysConf;
     $V = "";
     $formVars = array();
     if (!$PG_CONN) {
         echo _("NO DB connection");
     }
     if ($this->State != PLUGIN_STATE_READY) {
         return 0;
     }
     $uploadtree_pk = GetParm("item", PARM_INTEGER);
     if (empty($uploadtree_pk)) {
         return;
     }
     $upload_pk = GetParm("upload", PARM_INTEGER);
     if (empty($upload_pk)) {
         return;
     }
     if (!$this->uploadDao->isAccessible($upload_pk, Auth::getGroupId())) {
         $text = _("Permission Denied");
         return "<h2>{$text}</h2>";
     }
     $uploadtreeTablename = GetUploadtreeTableName($upload_pk);
     $warnings = array();
     $agent_pks_dict = $this->getAgentPksFromRequest($upload_pk);
     $agent_pks = array();
     foreach ($agent_pks_dict as $agent_name => $agent_pk) {
         if ($agent_pk === false) {
             $warnings[] = _("No information for agent: {$agent_name}");
         } else {
             $agent_pks[] = $agent_pk;
             $formVars["agentToInclude_" . $agent_name] = "1";
         }
     }
     $dltext = GetParm("output", PARM_STRING) == 'dltext';
     $formVars["dltext"] = $dltext;
     $NomostListNum = @$SysConf['SYSCONFIG']['NomostListNum'];
     $formVars["NomostListNum"] = $NomostListNum;
     $includeSubfolder = GetParm("doNotIncludeSubfolder", PARM_STRING) !== "yes";
     $formVars["includeSubfolder"] = $includeSubfolder;
     $ignore = GetParm("showContainers", PARM_STRING) !== "yes";
     $formVars["showContainers"] = !$ignore;
     $exclude = GetParm("exclude", PARM_STRING);
     $formVars["exclude"] = $exclude;
     $V .= $this->renderString("ui-license-list-form.html.twig", $formVars);
     $V .= "<hr/>";
     $lines = $this->createListOfLines($uploadtreeTablename, $uploadtree_pk, $agent_pks, $NomostListNum, $includeSubfolder, $exclude, $ignore);
     if (array_key_exists("warn", $lines)) {
         $warnings[] = $lines["warn"];
         unset($lines["warn"]);
     }
     foreach ($warnings as $warning) {
         $V .= "<br><b>{$warning}</b><br>";
     }
     if ($dltext) {
         $request = $this->getRequest();
         $itemId = intval($request->get('item'));
         $path = Dir2Path($itemId, $uploadtreeTablename);
         $fileName = $path[count($path) - 1]['ufile_name'] . ".txt";
         $headers = array("Content-Type" => "text", "Content-Disposition" => "attachment; filename=\"{$fileName}\"");
         $response = new Response(implode("\n", $lines), Response::HTTP_OK, $headers);
         return $response;
     } else {
         return $V . '<pre>' . implode("\n", $lines) . '</pre>';
     }
 }
Exemplo n.º 20
0
 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');
 }
Exemplo n.º 21
0
 /**
  * @brief Process the upload request.
  */
 protected function handleUpload(Request $request)
 {
     global $Plugins;
     define("UPLOAD_ERR_INVALID_FOLDER_PK", 100);
     define("UPLOAD_ERR_RESEND", 200);
     $uploadErrors = array(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);
     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 (empty($folderId)) {
         return array(false, $uploadErrors[UPLOAD_ERR_INVALID_FOLDER_PK], $description);
     }
     $public = $request->get('public');
     $publicPermission = $public == self::PUBLIC_ALL ? Auth::PERM_READ : Auth::PERM_NONE;
     $sourceFiles = trim($request->get(self::SOURCE_FILES_FIELD));
     $sourceFiles = $this->basicShEscaping($sourceFiles);
     $host = $request->get('host') ?: "localhost";
     if (preg_match('/[^a-z.0-9]/i', $host)) {
         $text = _("The given host is not valid.");
         return array(false, $text, $description);
     }
     if (!$this->check_if_host_is_allowed($host)) {
         $text = _("You are not allowed to upload from the chosen host.");
         return array(false, $text, $description);
     }
     $shortName = basename($sourceFiles);
     if (empty($shortName)) {
         $shortName = $sourceFiles;
     }
     if (strcmp($host, "localhost")) {
         $shortName = $host . ':' . $shortName;
     }
     $sourceFiles = $this->normalize_path($sourceFiles, $host);
     $sourceFiles = str_replace('|', '\\|', $sourceFiles);
     $sourceFiles = str_replace(' ', '\\ ', $sourceFiles);
     $sourceFiles = str_replace("\t", "\\t", $sourceFiles);
     if ($sourceFiles == FALSE) {
         $text = _("failed to normalize/validate given path");
         return array(false, $text, $description);
     }
     if ($this->check_by_whitelist($sourceFiles) === FALSE) {
         $text = _("no suitable prefix found in the whitelist") . ", " . _("you are not allowed to upload this file");
         return array(false, $text, $description);
     }
     if (!$this->path_is_pattern($sourceFiles) && !$this->remote_file_exists($sourceFiles, $host)) {
         $text = _("'{$sourceFiles}' does not exist.\n");
         return array(false, $text, $description);
     }
     if (!$this->path_is_pattern($sourceFiles) && !$this->remote_file_permission($sourceFiles, $host, "r")) {
         $text = _("Have no READ permission on '{$sourceFiles}'.\n");
         return array(false, $text, $description);
     }
     if (!$this->path_is_pattern($sourceFiles) && is_file($sourceFiles) && filesize($sourceFiles) <= 0) {
         $text = _("You can not upload an empty file.\n");
         return array(false, $text, $description);
     }
     /* Create an upload record. */
     $uploadMode = 1 << 3;
     // code for "it came from web upload"
     $userId = Auth::getUserId();
     $groupId = Auth::getGroupId();
     $uploadId = JobAddUpload($userId, $groupId, $shortName, $sourceFiles, $description, $uploadMode, $folderId, $publicPermission);
     if (empty($uploadId)) {
         $text = _("Failed to insert upload record");
         return array(false, $text, $description);
     }
     /* Prepare the job: job "wget" */
     $jobpk = JobAddJob($userId, $groupId, "wget", $uploadId);
     if (empty($jobpk) || $jobpk < 0) {
         $text = _("Failed to insert upload record");
         return array(false, $text, $description);
     }
     $jq_args = "{$uploadId} - {$sourceFiles}";
     $jobqueuepk = JobQueueAdd($jobpk, "wget_agent", $jq_args, "no", NULL, $host);
     if (empty($jobqueuepk)) {
         $text = _("Failed to insert task 'wget' into job queue");
         return array(false, $text, $description);
     }
     $ErrorMsg = "";
     /* 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, $text, _($ErrorMsg));
     }
     $adj2nestplugin =& $Plugins[plugin_find_id("agent_adj2nest")];
     $adj2nest_jq_pk = $adj2nestplugin->AgentAdd($jobpk, $uploadId, $ErrorMsg, array());
     if ($adj2nest_jq_pk < 0) {
         return array(false, $text, _($ErrorMsg));
     }
     AgentCheckBoxDo($jobpk, $uploadId);
     $message = "";
     /** check if the scheudler is running */
     $status = GetRunnableJobList();
     if (empty($status)) {
         $message .= _("Is the scheduler running? ");
     }
     $Url = Traceback_uri() . "?mod=showjobs&upload={$uploadId}";
     $message .= "The file {$sourceFiles} has been uploaded. ";
     $keep = "It is <a href='{$Url}'>upload #" . $uploadId . "</a>.\n";
     return array(true, $message . $keep, $description);
 }
Exemplo n.º 22
0
/**
 * \brief Schedule delagent on upload ids
 *
 * \param $upload_pk_list -  upload ids, The string can be a comma-separated list of upload ids.
 * Or, use 'ALL' to specify all upload ids.
 */
function QueueUploadsOnDelagents($upload_pk_list)
{
    /* Get the users.default_bucketpool_fk */
    $user_pk = Auth::getUserId();
    $group_pk = Auth::getGroupId();
    if (!empty($upload_pk_list)) {
        foreach (explode(",", $upload_pk_list) as $upload_pk) {
            if (empty($upload_pk)) {
                continue;
            }
            // Create a job for the upload
            $jobpk = JobAddJob($user_pk, $group_pk, "Delete", $upload_pk);
            if (empty($jobpk) || $jobpk < 0) {
                echo "WARNING: Failed to schedule Delagent for Upload {$upload_pk}";
            }
            $jqargs = "DELETE UPLOAD {$upload_pk}";
            $jobqueuepk = JobQueueAdd($jobpk, "delagent", $jqargs, NULL, NULL);
            if (empty($jobqueuepk)) {
                echo "WARNING: Failed to schedule Delagent for Upload {$upload_pk}";
            }
            print "Delagent is queued to run on Upload: {$upload_pk}.\n";
        }
        /* for each $upload_pk */
    }
    // if $upload_pk is defined
    /* Tell the scheduler to check the queue. */
    $success = fo_communicate_with_scheduler("database", $output, $error_msg);
    if (!$success) {
        echo $error_msg . "\n" . $output;
    }
}
Exemplo n.º 23
0
 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;
 }
Exemplo n.º 24
0
/**
 * @brief Get uploads and folder info, starting from $ParentFolder.
 * The array is sorted by folder and upload name.
 * Folders that are empty do not show up.
 * This is recursive!
 * NOTE: If there is a recursive loop in the folder table, then
 * this will loop INFINITELY.
 *
 * @param int $ParentFolder folder_pk, -1 for users root folder
 * @param string $FolderPath Used for recursion, caller should not specify.
 * @param Auth::PERM_READ | Auth::PERM_WRITE
 * @return array of {upload_pk, upload_desc, name, folder}
 */
function FolderListUploadsRecurse($ParentFolder = -1, $FolderPath = '', $perm = Auth::PERM_READ)
{
    global $PG_CONN;
    if (empty($PG_CONN)) {
        return array();
    }
    if (empty($ParentFolder)) {
        return array();
    }
    if ($perm != Auth::PERM_READ && ($perm = Auth::PERM_WRITE)) {
        return array();
    }
    if ($ParentFolder == "-1") {
        $ParentFolder = FolderGetTop();
    }
    $groupId = Auth::getGroupId();
    /* @var $uploadDao UploadDao */
    $uploadDao = $GLOBALS['container']->get('dao.upload');
    $List = array();
    /* Get list of uploads */
    /** mode 1<<1 = upload_fk **/
    $sql = "SELECT upload_pk, upload_desc, ufile_name, folder_name FROM folder,foldercontents,uploadtree, upload\n    WHERE \n        foldercontents.parent_fk = '{$ParentFolder}'\n    AND foldercontents.foldercontents_mode = " . FolderDao::MODE_UPLOAD . "\n    AND foldercontents.child_id = upload.upload_pk\n    AND folder.folder_pk = {$ParentFolder}\n    AND uploadtree.upload_fk = upload.upload_pk\n    AND uploadtree.parent is null\n    ORDER BY uploadtree.ufile_name,upload.upload_desc";
    $result = pg_query($PG_CONN, $sql);
    DBCheckResult($result, $sql, __FILE__, __LINE__);
    while ($R = pg_fetch_assoc($result)) {
        if (empty($R['upload_pk'])) {
            continue;
        }
        if ($perm == Auth::PERM_READ && !$uploadDao->isAccessible($R['upload_pk'], $groupId)) {
            continue;
        }
        if ($perm == Auth::PERM_WRITE && !$uploadDao->isEditable($R['upload_pk'], $groupId)) {
            continue;
        }
        $New['upload_pk'] = $R['upload_pk'];
        $New['upload_desc'] = $R['upload_desc'];
        $New['name'] = $R['ufile_name'];
        $New['folder'] = $FolderPath . "/" . $R['folder_name'];
        array_push($List, $New);
    }
    pg_free_result($result);
    /* Get list of subfolders and recurse */
    /** mode 1<<0 = folder_pk **/
    $sql = "SELECT A.child_id AS id,B.folder_name AS folder,B.folder_name AS subfolder\n\tFROM foldercontents AS A\n\tINNER JOIN folder AS B ON A.parent_fk = B.folder_pk\n\tAND A.foldercontents_mode = " . FolderDao::MODE_FOLDER . "\n\tAND A.parent_fk = '{$ParentFolder}'\n  AND B.folder_pk = {$ParentFolder}\n\tORDER BY B.folder_name;";
    $result = pg_query($PG_CONN, $sql);
    DBCheckResult($result, $sql, __FILE__, __LINE__);
    while ($R = pg_fetch_assoc($result)) {
        if (empty($R['id'])) {
            continue;
        }
        /* RECURSE! */
        $SubList = FolderListUploadsRecurse($R['id'], $FolderPath . "/" . $R['folder'], $perm);
        $List = array_merge($List, $SubList);
    }
    pg_free_result($result);
    /* Return findings */
    return $List;
}
Exemplo n.º 25
0
 /**
  * @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);
 }
Exemplo n.º 26
0
 /**
  * @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");
 }
Exemplo n.º 27
0
 /**
  * \brief This function returns the scheduler status.
  */
 public function Output()
 {
     $uTime = microtime(true);
     $V = "";
     $Upload = GetParm("upload", PARM_INTEGER);
     /** @var UploadDao $uploadDao */
     $uploadDao = $GLOBALS['container']->get('dao.upload');
     if (!$uploadDao->isAccessible($Upload, Auth::getGroupId())) {
         $text = _("Permission Denied");
         return "<h2>{$text}</h2>";
     }
     $Item = GetParm("item", PARM_INTEGER);
     if (!$Item) {
         return _('No item selected');
     }
     $updcache = GetParm("updcache", PARM_INTEGER);
     $tagbucket = GetParm("tagbucket", PARM_INTEGER);
     $this->uploadtree_tablename = GetUploadtreeTableName($Upload);
     /* Remove "updcache" from the GET args and set $this->UpdCache
      * This way all the url's based on the input args won't be
      * polluted with updcache
      * Use Traceback_parm_keep to ensure that all parameters are in order 
      */
     $CacheKey = "?mod=" . $this->Name . Traceback_parm_keep(array("upload", "item", "folder", "ars"));
     if ($updcache) {
         $_SERVER['REQUEST_URI'] = preg_replace("/&updcache=[0-9]*/", "", $_SERVER['REQUEST_URI']);
         unset($_GET['updcache']);
         $V = ReportCachePurgeByKey($CacheKey);
     } else {
         $V = ReportCacheGet($CacheKey);
     }
     if (!empty($tagbucket)) {
         $bucketagent_pk = GetParm("bapk", PARM_INTEGER);
         $bucket_pk = GetParm("bpk", PARM_INTEGER);
         $bucketpool_pk = GetParm("bp", PARM_INTEGER);
         $nomosagent_pk = GetParm("napk", PARM_INTEGER);
         $this->TagBucket($Upload, $Item, $bucketagent_pk, $bucket_pk, $bucketpool_pk, $nomosagent_pk);
     }
     $Cached = !empty($V);
     if (!$Cached) {
         $V .= "<font class='text'>\n";
         $Children = GetNonArtifactChildren($Item, $this->uploadtree_tablename);
         if (count($Children) == 0) {
             // no children, display View-Meta micromenu
             $V .= Dir2Browse($this->Name, $Item, NULL, 1, "View-Meta", -1, '', '', $this->uploadtree_tablename) . "<P />\n";
         } else {
             // has children, display Browse micormenu
             $V .= Dir2Browse($this->Name, $Item, NULL, 1, "Browse", -1, '', '', $this->uploadtree_tablename) . "<P />\n";
         }
         if (!empty($Upload)) {
             $Uri = preg_replace("/&item=([0-9]*)/", "", Traceback());
             $V .= $this->ShowUploadHist($Item, $Uri);
         }
         $V .= "</font>\n";
         $text = _("Loading...");
     }
     $Time = microtime(true) - $uTime;
     // convert usecs to secs
     $text = _("Elapsed time: %.2f seconds");
     $V .= sprintf("<p><small>{$text}</small>", $Time);
     if ($Cached) {
         $text = _("cached");
         $text1 = _("Update");
         echo " <i>{$text}</i>   <a href=\"{$_SERVER['REQUEST_URI']}&updcache=1\"> {$text1} </a>";
     } else {
         if ($Time > 0.5) {
             ReportCachePut($CacheKey, $V);
         }
     }
     return $V;
 }
Exemplo n.º 28
0
 /**
  * @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;
 }
Exemplo n.º 29
0
 /**
  * \brief Given a filename, return all uploadtree.
  * \param $Item     uploadtree_pk of tree to search, if empty, do global search
  * \param $Filename filename or pattern to search for, false if unused
  * \param $tag      tag (or tag pattern mytag%) to search for, false if unused
  * \param $Page     display page number
  * \param $SizeMin  Minimum file size, -1 if unused
  * \param $SizeMax  Maximum file size, -1 if unused
  * \param $searchtype "containers" or "allfiles"
  * \return array of uploadtree recs.  Each record contains uploadtree_pk, parent, 
  *         upload_fk, pfile_fk, ufile_mode, and ufile_name
  */
 function GetResults($Item, $Filename, $tag, $Page, $SizeMin, $SizeMax, $searchtype, $License, $Copyright)
 {
     global $PG_CONN;
     $UploadtreeRecs = array();
     // uploadtree record array to return
     $NeedTagfileTable = true;
     $NeedTaguploadtreeTable = true;
     if ($Item) {
         /* Find lft and rgt bounds for this $Uploadtree_pk  */
         $row = $this->uploadDao->getUploadEntry($Item);
         if (empty($row)) {
             $text = _("Invalid URL, nonexistant item");
             return "<h2>{$text} {$Item}</h2>";
         }
         $lft = $row["lft"];
         $rgt = $row["rgt"];
         $upload_pk = $row["upload_fk"];
         /* Check upload permission */
         if (!$this->uploadDao->isAccessible($upload_pk, Auth::getGroupId())) {
             return $UploadtreeRecs;
         }
     }
     /* Start the result select stmt */
     $SQL = "SELECT DISTINCT uploadtree_pk, parent, upload_fk, uploadtree.pfile_fk, ufile_mode, ufile_name FROM uploadtree";
     if (!empty($License)) {
         $SQL .= ", ( SELECT license_ref.rf_shortname, license_file.rf_fk, license_file.pfile_fk\n                  FROM license_file JOIN license_ref ON license_file.rf_fk = license_ref.rf_pk) AS pfile_ref";
     }
     if (!empty($Copyright)) {
         $SQL .= ",copyright";
     }
     /* Figure out the tag_pk's of interest */
     if (!empty($tag)) {
         $sql = "select tag_pk from tag where tag ilike '{$tag}'";
         $result = pg_query($PG_CONN, $sql);
         DBCheckResult($result, $sql, __FILE__, __LINE__);
         if (pg_num_rows($result) < 1) {
             /* tag doesn't match anything, so no results are possible */
             pg_free_result($result);
             return $UploadtreeRecs;
         }
         /* Make a list of the tag_pk's that satisfy the criteria */
         $tag_pk_array = pg_fetch_all($result);
         pg_free_result($result);
         /* add the tables needed for the tag query */
         $sql = "select tag_file_pk from tag_file limit 1";
         $result = pg_query($PG_CONN, $sql);
         DBCheckResult($result, $sql, __FILE__, __LINE__);
         if (pg_num_rows($result) < 1) {
             /* tag_file didn't have data, don't add the tag_file table for tag query */
             $NeedTagfileTable = false;
         } else {
             $SQL .= ", tag_file";
         }
         pg_free_result($result);
         /* add the tables needed for the tag query */
         $sql = "select tag_uploadtree_pk from tag_uploadtree limit 1";
         $result = pg_query($PG_CONN, $sql);
         DBCheckResult($result, $sql, __FILE__, __LINE__);
         if (pg_num_rows($result) < 1) {
             /* tag_uploadtree didn't have data, don't add the tag_uploadtree table for tag query */
             $NeedTaguploadtreeTable = false;
         } else {
             $SQL .= ", tag_uploadtree";
         }
         pg_free_result($result);
         if (!$NeedTagfileTable && !$NeedTaguploadtreeTable) {
             $SQL .= ", tag_file, tag_uploadtree";
         }
     }
     /* do we need the pfile table? Yes, if any of these are a search critieria.  */
     if (!empty($SizeMin) or !empty($SizeMax)) {
         $SQL .= ", pfile where pfile_pk=uploadtree.pfile_fk ";
         $NeedAnd = true;
     } else {
         $SQL .= " where ";
         $NeedAnd = false;
     }
     /* add the tag conditions */
     if (!empty($tag)) {
         if ($NeedAnd) {
             $SQL .= " AND";
         }
         $SQL .= "(";
         $NeedOr = false;
         foreach ($tag_pk_array as $tagRec) {
             if ($NeedOr) {
                 $SQL .= " OR";
             }
             $SQL .= "(";
             $tag_pk = $tagRec['tag_pk'];
             if ($NeedTagfileTable && $NeedTaguploadtreeTable) {
                 $SQL .= "(uploadtree.pfile_fk=tag_file.pfile_fk and tag_file.tag_fk={$tag_pk}) or (uploadtree_pk=tag_uploadtree.uploadtree_fk and tag_uploadtree.tag_fk={$tag_pk}) ";
             } else {
                 if ($NeedTaguploadtreeTable) {
                     $SQL .= "uploadtree_pk=tag_uploadtree.uploadtree_fk and tag_uploadtree.tag_fk={$tag_pk}";
                 } else {
                     if ($NeedTagfileTable) {
                         $SQL .= "uploadtree.pfile_fk=tag_file.pfile_fk and tag_file.tag_fk={$tag_pk}";
                     } else {
                         $SQL .= "(uploadtree.pfile_fk=tag_file.pfile_fk and tag_file.tag_fk={$tag_pk}) or (uploadtree_pk=tag_uploadtree.uploadtree_fk and tag_uploadtree.tag_fk={$tag_pk}) ";
                     }
                 }
             }
             $SQL .= ")";
             $NeedOr = 1;
         }
         $NeedAnd = 1;
         $SQL .= ")";
     }
     if ($Filename) {
         $Filename = str_replace("'", "''", $Filename);
         // protect DB
         if ($NeedAnd) {
             $SQL .= " AND";
         }
         $SQL .= " ufile_name ilike '{$Filename}'";
         $NeedAnd = 1;
     }
     if (!empty($SizeMin)) {
         if ($NeedAnd) {
             $SQL .= " AND";
         }
         $SQL .= " pfile.pfile_size >= {$SizeMin}";
         $NeedAnd = 1;
     }
     if (!empty($SizeMax)) {
         if ($NeedAnd) {
             $SQL .= " AND";
         }
         $SQL .= " pfile.pfile_size <= {$SizeMax}";
         $NeedAnd = 1;
     }
     if ($Item) {
         if ($NeedAnd) {
             $SQL .= " AND";
         }
         $SQL .= "  upload_fk = {$upload_pk} AND lft >= {$lft} AND rgt <= {$rgt}";
         $NeedAnd = 1;
     }
     /* search only containers */
     $dir_ufile_mode = 536888320;
     if ($searchtype == 'containers') {
         if ($NeedAnd) {
             $SQL .= " AND";
         }
         $SQL .= " ((ufile_mode & (1<<29))!=0) AND ((ufile_mode & (1<<28))=0)";
         $NeedAnd = 1;
     }
     if ($searchtype == 'directory') {
         if ($NeedAnd) {
             $SQL .= " AND";
         }
         $SQL .= " ((ufile_mode & (1<<29))!=0) AND ((ufile_mode & (1<<28))=0) AND (ufile_mode != {$dir_ufile_mode}) and pfile_fk != 0";
         $NeedAnd = 1;
     }
     /** license and copyright */
     if (!empty($License)) {
         if ($NeedAnd) {
             $SQL .= " AND";
         }
         $SQL .= " uploadtree.pfile_fk=pfile_ref.pfile_fk and pfile_ref.rf_shortname ilike '{$License}'";
         $NeedAnd = 1;
     }
     if (!empty($Copyright)) {
         if ($NeedAnd) {
             $SQL .= " AND";
         }
         $SQL .= " uploadtree.pfile_fk=copyright.pfile_fk and copyright.content ilike '%{$Copyright}%'";
     }
     $Offset = $Page * $this->MaxPerPage;
     $SQL .= " ORDER BY ufile_name, uploadtree.pfile_fk";
     $SQL .= " LIMIT {$this->MaxPerPage} OFFSET {$Offset};";
     $result = pg_query($PG_CONN, $SQL);
     DBCheckResult($result, $SQL, __FILE__, __LINE__);
     if (pg_num_rows($result)) {
         while ($row = pg_fetch_assoc($result)) {
             if (!$this->uploadDao->isAccessible($row['upload_fk'], Auth::getGroupId())) {
                 continue;
             }
             $UploadtreeRecs[] = $row;
         }
     }
     pg_free_result($result);
     return $UploadtreeRecs;
 }
Exemplo n.º 30
0
 /**
  * \brief Given an $Uploadtree_pk, display:
  *   - The histogram for the directory BY LICENSE.
  *   - The file listing for the directory.
  */
 private function showUploadHist(ItemTreeBounds $itemTreeBounds)
 {
     $groupId = Auth::getGroupId();
     $selectedAgentId = GetParm('agentId', PARM_INTEGER);
     $tag_pk = GetParm("tag", PARM_INTEGER);
     $uploadId = $itemTreeBounds->getUploadId();
     $scannerAgents = array_keys($this->agentNames);
     $scanJobProxy = new ScanJobProxy($this->agentDao, $uploadId);
     $scannerVars = $scanJobProxy->createAgentStatus($scannerAgents);
     $agentMap = $scanJobProxy->getAgentMap();
     $vars = array('agentId' => GetParm('agentId', PARM_INTEGER), 'agentShowURI' => Traceback_uri() . '?mod=' . Traceback_parm(), 'agentMap' => $agentMap, 'scanners' => $scannerVars);
     $selectedAgentIds = empty($selectedAgentId) ? $scanJobProxy->getLatestSuccessfulAgentIds() : $selectedAgentId;
     if (!empty($agentMap)) {
         $licVars = $this->createLicenseHistogram($itemTreeBounds->getItemId(), $tag_pk, $itemTreeBounds, $selectedAgentIds, $groupId);
         $vars = array_merge($vars, $licVars);
     }
     $this->licenseProjector = new LicenseMap($this->getObject('db.manager'), $groupId, LicenseMap::CONCLUSION, true);
     $dirVars = $this->countFileListing($itemTreeBounds);
     $childCount = $dirVars['iTotalRecords'];
     /***************************************
      * Problem: $ChildCount can be zero if you have a container that does not
      * unpack to a directory.  For example:
      * file.gz extracts to archive.txt that contains a license.
      * Same problem seen with .pdf and .Z files.
      * Solution: if $ChildCount == 0, then just view the license!
      *
      * $ChildCount can also be zero if the directory is empty.
      * **************************************/
     if ($childCount == 0) {
         return new RedirectResponse("?mod=view-license" . Traceback_parm_keep(array("upload", "item")));
     }
     $vars['licenseUri'] = Traceback_uri() . "?mod=popup-license&rf=";
     $vars['bulkUri'] = Traceback_uri() . "?mod=popup-license";
     return array_merge($vars, $dirVars);
 }