-
-
diff --git a/front_end/openVRE/public/getdata/objstorage/lib/obj_storage.inc.php b/front_end/openVRE/public/getdata/objstorage/lib/obj_storage.inc.php
index b8c30cf0..d2522a3c 100644
--- a/front_end/openVRE/public/getdata/objstorage/lib/obj_storage.inc.php
+++ b/front_end/openVRE/public/getdata/objstorage/lib/obj_storage.inc.php
@@ -4,7 +4,7 @@
function getOpenstackUser($vaultUrl, $vaultToken, $accessToken, $vaultRolename, $username) {
$vaultClient = new VaultClient($vaultUrl, $vaultToken, $accessToken, $vaultRolename, $username);
- $vaultKey = $_SESSION['User']['Vault']['vaultKey'];
+ $vaultKey = $_SESSION['userVaultInfo']['vaultKey'];
$credentials = $vaultClient->retrieveDatafromVault('Swift', $vaultKey, $vaultUrl, 'secret/mysecret/data/', $_SESSION['User']['_id'] . '_credentials.txt');
if ($credentials) {
diff --git a/front_end/openVRE/public/getdata/sampleDataList.php b/front_end/openVRE/public/getdata/sampleDataList.php
index 4fe5577e..48dcbd59 100644
--- a/front_end/openVRE/public/getdata/sampleDataList.php
+++ b/front_end/openVRE/public/getdata/sampleDataList.php
@@ -1,19 +1,10 @@
$sampleName";
-}
- */
?>
@@ -21,120 +12,120 @@
-
-
-
-
-
-
-
-
-
-
-
- -
- Home
-
-
- -
- Get Data
-
-
- -
- From Example Dataset
-
-
-
-
-
-
Import Example Dataset
-
-
-
-
-
-
-
-
-
-
-
-
-
-$txts){
- print "
$subTitle";
- foreach($txts as $txt){
- print "
$txt
";
- }
- }
- unset($_SESSION['errorData']);
- ?>
-
-
-
-
-
-
+
\ No newline at end of file
diff --git a/front_end/openVRE/public/htmlib/globals.js.inc.php b/front_end/openVRE/public/htmlib/globals.js.inc.php
index 7e61a71e..b41682eb 100644
--- a/front_end/openVRE/public/htmlib/globals.js.inc.php
+++ b/front_end/openVRE/public/htmlib/globals.js.inc.php
@@ -1,32 +1,18 @@
find(array(),array('country'=>1),array('country'=>1)) )) as $v){
- $countries[$v['_id']] = $v['country'];
-}
-
-echo 'var countriesSelect = \'
\';';
-
// ROLES VAR (LIST)
echo '
var rolesList = \'\';';
@@ -35,19 +21,19 @@
echo '
var rolesSelect = \'
\';';
+echo '\';';
// ROLES COLORS
echo '
var rolesColor = {';
-foreach($GLOBALS['ROLES_COLOR'] as $k => $v):
- if($k == '2') echo $k.':null,';
- else echo $k.':"'.$v.'",';
+foreach ($GLOBALS['ROLES_COLOR'] as $k => $v):
+ if ($k == '2') echo $k . ':null,';
+ else echo $k . ':"' . $v . '",';
endforeach;
echo '};';
@@ -55,21 +41,21 @@
echo '
-var diskLimit = '.$GLOBALS['DISKLIMIT'].';';
+var diskLimit = ' . $GLOBALS['DISKLIMIT'] . ';';
// MAX UPLOAD SIZE
echo '
-var maxUpSize = '.$GLOBALS['MAXSIZEUPLOAD'].';';
+var maxUpSize = ' . $GLOBALS['MAXSIZEUPLOAD'] . ';';
// FILE STATE COLORS
echo '
var fileStateColor = {';
-foreach($GLOBALS['STATES_COLOR'] as $k => $v):
- echo $k.':"'.$v.'",';
+foreach ($GLOBALS['STATES_COLOR'] as $k => $v):
+ echo $k . ':"' . $v . '",';
endforeach;
echo '};';
@@ -78,8 +64,8 @@
echo '
var fileMessageColor = {';
-foreach($GLOBALS['FILE_MSG_COLOR'] as $k => $v):
- echo $k.':"'.$v.'",';
+foreach ($GLOBALS['FILE_MSG_COLOR'] as $k => $v):
+ echo $k . ':"' . $v . '",';
endforeach;
echo '};';
@@ -105,16 +91,13 @@
echo '
var labelsUsersPieChart = {';
-foreach($GLOBALS['ROLES'] as $k => $v):
- echo $count_tou.':\''.$v.'\',';
- $count_tou ++;
+foreach ($GLOBALS['ROLES'] as $k => $v):
+ echo $count_tou . ':\'' . $v . '\',';
+ $count_tou++;
endforeach;
echo '};';
echo '
-var baseURL = \''.$GLOBALS['BASEURL'].'\';';
-
-
-?>
+var baseURL = \'' . $GLOBALS['BASEURL'] . '\';';
diff --git a/front_end/openVRE/public/htmlib/header.inc.php b/front_end/openVRE/public/htmlib/header.inc.php
index 137e89d0..7f01d2f7 100644
--- a/front_end/openVRE/public/htmlib/header.inc.php
+++ b/front_end/openVRE/public/htmlib/header.inc.php
@@ -87,12 +87,6 @@
case 'adminJobs':
case 'myNewTools':
case 'dashboard':
- case 'eush_projects':
- case 'eush_ega':
- case 'eush_ega_datasets':
- case 'eush_cardiogwas':
- case 'eush_cardiogwas_table':
- case 'eush_cardiogwas_table_step_II':
case 'datasets':
case 'logs': ?>
@@ -221,16 +215,6 @@
case 'jsonTestValidator':
case 'dashboard':
case 'datasets':
- case 'eush_projects':
- case 'eush_subjects':
- case 'eush_experiments':
- case 'eush_subjects_auth':
- case 'eush_experiments_auth':
- case 'eush_ega':
- case 'eush_ega_datasets':
- case 'eush_cardiogwas':
- case 'eush_cardiogwas_table':
- case 'eush_cardiogwas_table_step_II':
case 'sampleDataList':
case 'dataFromTxt':
case 'dataFromID':
diff --git a/front_end/openVRE/public/htmlib/js.inc.php b/front_end/openVRE/public/htmlib/js.inc.php
index fabf6a91..a838f696 100644
--- a/front_end/openVRE/public/htmlib/js.inc.php
+++ b/front_end/openVRE/public/htmlib/js.inc.php
@@ -59,16 +59,6 @@
@@ -275,43 +265,6 @@
case 'usrProfile': ?>
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
From Catalogue
-
";
- return $dma[0]."/".$dma[1]."/".$dma[2]." - ".$hms[0].":".$hms[1];
-
+ return $dma[0] . "/" . $dma[1] . "/" . $dma[2] . " - " . $hms[0] . ":" . $hms[1];
}
-function returnHumanDateDashboard($q){
+function returnHumanDateDashboard($q)
+{
$d = explode("*", $q);
$dma = explode("/", $d[0]);
$hms = explode(":", $d[1]);
- return "
".$dma[0]."/".$dma[1]."/".$dma[2]." ".$hms[0].":".$hms[1]."";
+ return "
" . $dma[0] . "/" . $dma[1] . "/" . $dma[2] . " " . $hms[0] . ":" . $hms[1] . "";
}
-function is_multi_array( $arr ) {
- rsort( $arr );
- return isset( $arr[0] ) && is_array( $arr[0] );
+function is_multi_array($arr)
+{
+ rsort($arr);
+ return isset($arr[0]) && is_array($arr[0]);
}
-function maxlength($in, $length) {
-
- return strlen($in) > $length ? substr($in,0,$length)."..." : $in;
+function maxlength($in, $length)
+{
+ return strlen($in) > $length ? substr($in, 0, $length) . "..." : $in;
}
-function getSize($bytes) {
+function getSize($bytes)
+{
if ($bytes >= 1073741824) {
- $bytes = (number_format($bytes / 1073741824, 2) + 0). ' GB';
- }
- elseif ($bytes >= 1048576) {
+ $bytes = (number_format($bytes / 1073741824, 2) + 0) . ' GB';
+ } elseif ($bytes >= 1048576) {
$bytes = (number_format($bytes / 1048576, 2) + 0) . ' MB';
- }
- elseif ($bytes >= 1024) {
- $bytes = (number_format($bytes / 1024, 2) + 0). ' KB';
- }
- elseif ($bytes >= 0) {
- $bytes = ($bytes + 0). ' B';
+ } elseif ($bytes >= 1024) {
+ $bytes = (number_format($bytes / 1024, 2) + 0) . ' KB';
+ } elseif ($bytes >= 0) {
+ $bytes = ($bytes + 0) . ' B';
}
return $bytes;
-
}
-function cleanName($str) {
+function cleanName($str)
+{
return preg_replace('/[\(\) \/\,\#\@\>\<\$\%\&\!\?\¿\¡\*\'\"\{\}\:\;\º\ª\ç]/', '-', $str);
-
}
-function secondsToTime($seconds) {
- $dtF = new \DateTime('@0');
- $dtT = new \DateTime("@$seconds");
- return $dtF->diff($dtT)->format('%H:%I:%S');
+function secondsToTime($seconds)
+{
+ $dtF = new \DateTime('@0');
+ $dtT = new \DateTime("@$seconds");
+ return $dtF->diff($dtT)->format('%H:%I:%S');
}
-function momentToTime($moment) {
+function momentToTime($moment)
+{
- if ($moment){
- $dtime = DateTime::createFromFormat("Y/m/d*H:i:s",$moment);
- $timestamp = $dtime->getTimestamp();
- return $timestamp;
- }else{
- return 0;
- }
+ if ($moment) {
+ $dtime = DateTime::createFromFormat("Y/m/d*H:i:s", $moment);
+ $timestamp = $dtime->getTimestamp();
+ return $timestamp;
+ } else {
+ return 0;
+ }
}
-
-?>
diff --git a/front_end/openVRE/public/phplib/getdata.inc.php b/front_end/openVRE/public/phplib/getdata.inc.php
index 424a2628..72bce1b7 100644
--- a/front_end/openVRE/public/phplib/getdata.inc.php
+++ b/front_end/openVRE/public/phplib/getdata.inc.php
@@ -809,15 +809,13 @@ function getData_fromRepository($url, $datatype, $filetype, $description, $oeb_d
function getSampleDataList($status = 1, $filter_tool_status = true)
{
-
- $ft;
if ($filter_tool_status) {
$fa = indexArray($GLOBALS['toolsCol']->find(array('status' => 1), array('_id' => 1)));
$fu = indexArray($GLOBALS['visualizersCol']->find(array('status' => 1), array('_id' => 1)));
$tools_active = array_keys(array_merge($fa, $fu));
// if common/anon user, list sampledata for active tools
- if ($_SESSION['User']['Type'] == 3 || $_SESSION['User']['Type'] == 2) {
+ if ($_SESSION['User']['Type'] == UserType::Guest->value || $_SESSION['User']['Type'] == UserType::Registered->value) {
$ft = $GLOBALS['sampleDataCol']->find(array(
'$or' => array(
array("status" => $status, "tool" => array('$not' => array('$exists' => 1))),
@@ -826,11 +824,11 @@ function getSampleDataList($status = 1, $filter_tool_status = true)
), array('_id' => 1));
// if admin user, list sampledata regardless tool status
- } elseif ($_SESSION['User']['Type'] == 0) {
+ } elseif ($_SESSION['User']['Type'] == UserType::Admin->value) {
$ft = $GLOBALS['sampleDataCol']->find(array('status' => $status), array('_id' => 1));
// if tool dev user, list sampledata for active tools + its own tools
- } elseif ($_SESSION['User']['Type'] == 1) {
+ } elseif ($_SESSION['User']['Type'] == UserType::ToolDev->value) {
$fr = $GLOBALS['toolsCol']->find(array('status' => 3, '_id' => array('$in' => $_SESSION['User']['ToolsDev'])), array('_id' => 1));
$tools_owned = array_keys(iterator_to_array($fr));
$ft = $GLOBALS['sampleDataCol']->find(array(
@@ -849,9 +847,9 @@ function getSampleDataList($status = 1, $filter_tool_status = true)
// get sampleData
-function getSampleData($sampleData)
+function getSampleData($sampleDataId)
{
- return $GLOBALS['sampleDataCol']->findOne(['_id' => $sampleData]);
+ return $GLOBALS['sampleDataCol']->findOne(['_id' => $sampleDataId]);
}
diff --git a/front_end/openVRE/public/phplib/linkedaccount.inc.php b/front_end/openVRE/public/phplib/linkedaccount.inc.php
index 1cf3333a..4214d522 100644
--- a/front_end/openVRE/public/phplib/linkedaccount.inc.php
+++ b/front_end/openVRE/public/phplib/linkedaccount.inc.php
@@ -1,203 +1,73 @@
uploadKeystoVault_check($data);
-
- // Update user data with vault key
- $_SESSION['User']['linked_accounts']['Vault']['vaultKey'] = $key;
- updateUser($_SESSION['User']);
-
- //var_dump($key);
-
- //var_dump($r);
-
- if (!$key) {
- $_SESSION['errorData']['Error'][] = "Failed to link MN account";
- $_SESSION['formData'] = $postData;
- redirect($_SERVER['HTTP_REFERER']);
- }
-
- $_SESSION['errorData']['Info'][] = "MN account successfully linked.";
- //redirect($GLOBALS['BASEURL'] . "user/usrProfile.php#tab_1_4");
- redirect($_SERVER['HTTP_REFERER']);
-
- } else {
- handleInvalidAction();
- };
+ default:
+ $_SESSION['errorData']['Error'][] = "Account of type '$accountType' is not yet supported.";
+ redirect($_SERVER['HTTP_REFERER']);
+ }
}
- */
-
-function handleSSHAccount($action, $site_id, $postData){
-
+function handleSSHAccount($action, $userId, $site_id, $postData)
+{
$data = [];
if ($action === "new") {
- // Check if the credentials are already saved
-
- if (isset($postData['private_key'], $postData['public_key'])) {
+ // Check if the credentials are already saved
+
+ if (isset($postData['private_key'], $postData['public_key'])) {
// If credentials are provided, use them directly
if (isset($_SESSION['User']['credentials']['timestamp'])) {
$savedTime = $_SESSION['User']['credentials']['timestamp'];
@@ -207,62 +77,58 @@ function handleSSHAccount($action, $site_id, $postData){
// Check if the timestamp is more than 2 hours old (validity check)
if (($currentTime - $savedTime) > 7200) {
$_SESSION['errorData']['Warning'][] = "Credentials were saved more than 2 hours ago. Please update them.";
- $accessToken = $_SESSION['User']['Token']['access_token'];
+ $accessToken = $_SESSION['userToken']['access_token'];
} else {
$_SESSION['errorData']['Info'][] = "Credentials are already saved and still valid.";
- $accessToken = $_SESSION['User']['Token']['access_token'];
- return;
+ $accessToken = $_SESSION['userToken']['access_token'];
+ return;
}
}
-
- } elseif (isset($postData["save_credential"]) && $postData["save_credential"] == "true") {
-
- $accessToken = $_SESSION['User']['Token']['access_token'];
- $data['data']['SSH'] = [];
- $data['data']['SSH']['private_key'] = $postData['private_key'];
- $data['data']['SSH']['public_key'] = $postData['public_key'];
- $data['data']['SSH']['user_key'] = $postData['user_key'];
- $data['data']['SSH']['_id'] = $postData['_id'];
- $_SESSION['User']['credentials'] = [
- 'timestamp' => time() // Only store the timestamp
- ];
-
-
-
+ } elseif (isset($postData["save_credential"]) && $postData["save_credential"] == "true") {
+
+ $accessToken = $_SESSION['userToken']['access_token'];
+ $data['data']['SSH'] = [];
+ $data['data']['SSH']['private_key'] = $postData['private_key'];
+ $data['data']['SSH']['public_key'] = $postData['public_key'];
+ $data['data']['SSH']['user_key'] = $postData['user_key'];
+ $data['data']['SSH']['_id'] = $userId;
+ $_SESSION['User']['credentials'] = [
+ 'timestamp' => time() // Only store the timestamp
+ ];
+
+
+
$_SESSION['errorData']['Info'][] = "Credentials in the system, saving to Vault...";
} else {
- // Handle the case where app_id or app_secret is empty
- $_SESSION['errorData']['Error'][] = "Please provide both keys.";
- $_SESSION['formData'] = $postData;
- redirect($_SERVER['HTTP_REFERER']);
- }
-
+ // Handle the case where app_id or app_secret is empty
+ $_SESSION['errorData']['Error'][] = "Please provide both keys.";
+ $_SESSION['formData'] = $postData;
+ redirect($_SERVER['HTTP_REFERER']);
+ }
+ } elseif ($action === "update") {
+ // Add logic for handling MN account and uploading credentials to Vault for "update" action
- } elseif ($action === "update") {
- // Add logic for handling MN account and uploading credentials to Vault for "update" action
-
if (!empty($postData['private_key']) && !empty($postData['public_key'])) {
- $accessToken = $_SESSION['User']['Token']['access_token'];
+ $accessToken = $_SESSION['userToken']['access_token'];
$data['data']['SSH'] = [];
$data['data']['SSH']['private_key'] = $postData['private_key'];
- $data['data']['SSH']['public_key'] = $postData['public_key'];
+ $data['data']['SSH']['public_key'] = $postData['public_key'];
$data['data']['SSH']['user_key'] = $postData['user_key'];
- $data['data']['SSH']['_id'] = $postData['_id'];
+ $data['data']['SSH']['_id'] = $userId;
$_SESSION['User']['credentials'] = [
- 'timestamp' => time() // Only store the timestamp
- ];
+ 'timestamp' => time() // Only store the timestamp
+ ];
$_SESSION['errorData']['Info'][] = "Credentials in the system, saving to Vault...";
- } else {
- // Handle the case where app_id or app_secret is empty
- $_SESSION['errorData']['Error'][] = "Please provide both keys.";
- $_SESSION['formData'] = $postData;
- redirect($_SERVER['HTTP_REFERER']);
- }
-
- } elseif ($action === "delete") {
- // Reset data for "delete" action
+ } else {
+ // Handle the case where app_id or app_secret is empty
+ $_SESSION['errorData']['Error'][] = "Please provide both keys.";
+ $_SESSION['formData'] = $postData;
+ redirect($_SERVER['HTTP_REFERER']);
+ }
+ } elseif ($action === "delete") {
+ // Reset data for "delete" action
$data = [];
if (isset($postData['private_key'], $postData['public_key'])) {
$postData['private_key'] = null;
@@ -270,13 +136,12 @@ function handleSSHAccount($action, $site_id, $postData){
$postData['user_key'] = null;
}
$postData['timestamp'] = null;
- $postData['_id'] = null;
+ $userId = null;
#var_dump($postData);
$_SESSION['errorData']['Info'][] = "Credentials for user erased, please provide new ones.";
- if (isset($site_id)) {
- #echo 'aoooooooooooooooo';
+ if (isset($site_id)) {
$updateResult = $GLOBALS['sitesCol']->updateOne(
['_id' => $site_id], // Match document by siteId
['$set' => [ // Use the $unset operator to remove fields
@@ -286,7 +151,7 @@ function handleSSHAccount($action, $site_id, $postData){
]]
);
- // Check if the update was successful
+ // Check if the update was successful
if ($updateResult->getModifiedCount() > 0) {
$_SESSION['errorData']['Info'][] = "Credentials removed from the database.";
} else {
@@ -294,128 +159,120 @@ function handleSSHAccount($action, $site_id, $postData){
}
}
redirect($_SERVER['HTTP_REFERER']);
+ } else {
+ handleInvalidAction();
+ }
+ if (empty($postData['user_key'])) {
+ error_log("Error: 'username' is missing in postData.");
+ throw new Exception("Username is required.");
+ exit;
+ }
-
- } else {
- handleInvalidAction();
- }
-
- if (empty($postData['user_key'])) {
- error_log("Error: 'username' is missing in postData.");
- throw new Exception("Username is required.");
- exit;
- }
-
- $postData['user_key'] = $postData['user_key'] . '_' . $site_id;
- $vaultClient = new VaultClient(
- $GLOBALS['vaultUrl'],
- $_SESSION['User']['Vault']['vaultToken'],
- $accessToken,
- $_SESSION['User']['Vault']['vaultRolename'],
- $postData['username']
- );
+ $postData['user_key'] = $postData['user_key'] . '_' . $site_id;
+ $vaultClient = new VaultClient(
+ $GLOBALS['vaultUrl'],
+ $_SESSION['userVaultInfo']['vaultToken'],
+ $accessToken,
+ $_SESSION['userVaultInfo']['vaultRolename'],
+ $postData['username']
+ );
//var_dump($data);
- $key = $vaultClient->uploadKeystoVault($data);
+ $key = $vaultClient->uploadKeystoVault($data);
//echo ("key");
//var_dump($key);
$tokenTime = $vaultClient->getTokenExpirationTime($GLOBALS['vaultUrl'], $key);
//echo ("TOKEN TIME" . $tokenTime);
if ($tokenTime !== false) {
- $_SESSION['User']['Vault']['expires_in'] = $tokenTime;
+ $_SESSION['userVaultInfo']['expires_in'] = $tokenTime;
}
// Update user data with vault key
- $_SESSION['User']['Vault']['vaultKey'] = $key;
- updateUser($_SESSION['User']);
- if (!$key) {
- $_SESSION['errorData']['Error'][] = "Failed to link SSH account";
- $_SESSION['formData'] = $postData;
- redirect($_SERVER['HTTP_REFERER']);
- }
-
- $_SESSION['errorData']['Info'][] = "SSH account successfully linked.";
- redirect($_SERVER['HTTP_REFERER']);
+ $_SESSION['userVaultInfo']['vaultKey'] = $key;
+ updateUser($_SESSION['User']);
+ if (!$key) {
+ $_SESSION['errorData']['Error'][] = "Failed to link SSH account";
+ $_SESSION['formData'] = $postData;
+ redirect($_SERVER['HTTP_REFERER']);
+ }
+
+ $_SESSION['errorData']['Info'][] = "SSH account successfully linked.";
+ redirect($_SERVER['HTTP_REFERER']);
}
-function handleObjectStorageAccount($action, $postData){
+function handleObjectStorageAccount($action, $userId, $postData)
+{
$data = [];
echo $action;
var_dump($postData);
if ($action === "new") {
- //$data = [];
+ //$data = [];
// Check if the credentials are already saved
-
+
if (isset($postData['app_id'], $postData['app_secret'])) {
- // If credentials are provided, use them directly
- $accessToken = $_SESSION['User']['Token']['access_token'];
+ // If credentials are provided, use them directly
+ $accessToken = $_SESSION['userToken']['access_token'];
$_SESSION['errorData']['Info'][] = "Credentials are already saved, update the credentials if needed.";
-
} elseif (isset($postData['save_credential']) && $postData['save_credential'] == 'true') {
- // Add logic for handling MN account and uploading credentials to Vault
- $accessToken = $_SESSION['User']['Token']['access_token'];
- // You can customize this part based on how you obtain Swift credentials
- $data['data']['Swift'] = [];
- $data['data']['Swift']['app_id'] = $postData['app_id']; // Modify this
+ // Add logic for handling MN account and uploading credentials to Vault
+ $accessToken = $_SESSION['userToken']['access_token'];
+ // You can customize this part based on how you obtain Swift credentials
+ $data['data']['Swift'] = [];
+ $data['data']['Swift']['app_id'] = $postData['app_id']; // Modify this
$data['data']['Swift']['app_secret'] = $postData['app_secret'];
- $data['data']['Swift']['projectName'] = $postData['projectName']; // Modify this
+ $data['data']['Swift']['projectName'] = $postData['projectName']; // Modify this
$data['data']['Swift']['projectId'] = $postData['projectId'];
$data['data']['Swift']['domainName'] = $postData['domainName'];
$data['data']['Swift']['projectDomainId'] = $postData['projectDomainId'];
$data['data']['Swift']['user_key'] = $postData['user_key'];
- $data['data']['Swift']['_id'] = $postData['_id'];
+ $data['data']['Swift']['_id'] = $userId;
}
-
-
-
} elseif ($action === "update") {
- // Add logic for handling MN account and uploading credentials to Vault for "update" action
+ // Add logic for handling MN account and uploading credentials to Vault for "update" action
if (!empty($postData['app_id']) && !empty($postData['app_secret'])) {
-
- $accessToken = $_SESSION['User']['Token']['access_token'];
- #$accessToken = json_decode($Token, true);
-
+
+ $accessToken = $_SESSION['userToken']['access_token'];
+
$data['data']['Swift'] = [];
- $data['data']['Swift']['app_id'] = $postData['app_id']; // Modify this
+ $data['data']['Swift']['app_id'] = $postData['app_id']; // Modify this
$data['data']['Swift']['app_secret'] = $postData['app_secret']; // Modify this
$data['data']['Swift']['projectName'] = $postData['projectName']; // Modify this
- $data['data']['Swift']['projectId'] = $postData['projectId'];
- $data['data']['Swift']['domainName'] = $postData['domainName'];
+ $data['data']['Swift']['projectId'] = $postData['projectId'];
+ $data['data']['Swift']['domainName'] = $postData['domainName'];
$data['data']['Swift']['projectDomainId'] = $postData['projectDomainId'];
$data['data']['Swift']['user_key'] = $postData['user_key'];
- $data['data']['Swift']['_id'] = $postData['_id'];
+ $data['data']['Swift']['_id'] = $userId;
#$_SESSION['errorData']['Info'][] = "Credentials updated!";
} else {
// Handle the case where app_id or app_secret is empty
- $_SESSION['errorData']['Error'][] = "Please provide both app_id and app_secret.";
- $_SESSION['formData'] = $postData;
- redirect($_SERVER['HTTP_REFERER']);
+ $_SESSION['errorData']['Error'][] = "Please provide both app_id and app_secret.";
+ $_SESSION['formData'] = $postData;
+ redirect($_SERVER['HTTP_REFERER']);
}
-
} elseif ($action === "delete") {
- // Reset data for "delete" action
+ // Reset data for "delete" action
$data = [];
if (isset($postData['app_id'], $postData['app_secret'])) {
$postData['app_id'] = null;
$postData['app_secret'] = null;
$postData['projectName'] = null;
- $postData['projectId']= null;
- $postData['domainName']= null;
+ $postData['projectId'] = null;
+ $postData['domainName'] = null;
$postData['projectDomainId'] = null;
$postData['user_key'] = null;
- $postData['_id'] = null;
+ $postData['_id'] = null;
}
$postData['timestamp'] = null;
- $postData['_id'] = null;
+ $userId = null;
#var_dump($postData);
$_SESSION['errorData']['Info'][] = "Credentials for user erased, please provide new ones.";
- if (isset($site_id)) {
+ if (isset($site_id)) {
$updateResult = $GLOBALS['sitesCol']->updateOne(
['_id' => $site_id], // Match document by siteId
['$set' => [ // Use the $unset operator to remove fields
@@ -429,7 +286,7 @@ function handleObjectStorageAccount($action, $postData){
]]
);
- // Check if the update was successful
+ // Check if the update was successful
if ($updateResult->getModifiedCount() > 0) {
$_SESSION['errorData']['Info'][] = "Credentials removed from the database.";
} else {
@@ -441,9 +298,9 @@ function handleObjectStorageAccount($action, $postData){
$_SESSION['errorData']['Info'][] = "Credentials for user erased, please provide new ones.";
} else {
- handleInvalidAction();
- }
-
+ handleInvalidAction();
+ }
+
if (empty($postData['user_key'])) {
error_log("Error: 'username' is missing in postData.");
throw new Exception("Username is required.");
@@ -452,19 +309,19 @@ function handleObjectStorageAccount($action, $postData){
$postData['user_key'] = $postData['user_key'] . '_' . $site_id;
$vaultClient = new VaultClient(
- $GLOBALS['vaultUrl'],
- $_SESSION['User']['Vault']['vaultToken'],
- $accessToken,
- $_SESSION['User']['Vault']['vaultRolename'],
- $postData['user_key']
+ $GLOBALS['vaultUrl'],
+ $_SESSION['userVaultInfo']['vaultToken'],
+ $accessToken,
+ $_SESSION['userVaultInfo']['vaultRolename'],
+ $postData['user_key']
);
#echo 'Vault';
#var_dump($vaultClient);
#var_dump($data);
$key = $vaultClient->uploadKeystoVault($data);
// Update user data with vault key
- $_SESSION['User']['Vault']['vaultKey'] = $key;
- updateUser($_SESSION['User']);
+ $_SESSION['userVaultInfo']['vaultKey'] = $key;
+ updateUser($_SESSION['User']);
if (!$key) {
$_SESSION['errorData']['Error'][] = "Failed to link Swift account";
$_SESSION['formData'] = $postData;
@@ -472,77 +329,57 @@ function handleObjectStorageAccount($action, $postData){
}
$_SESSION['errorData']['Info'][] = "Swift account successfully linked.";
- redirect($_SERVER['HTTP_REFERER']);
+ redirect($_SERVER['HTTP_REFERER']);
}
-function handleEGAAccount($action, $postData) {
- $data = [];
- if ($action === "new") {
- $accessToken = json_decode($_SESSION['User']['JWT'], true)["access_token"];
- if (isset($postData['username'], $postData['password'])) {
- $_SESSION['errorData']['Info'][] = "Credentials are already saved, update the credentials if needed.";
-
- } elseif (isset($postData['save_credential']) && $postData['save_credential'] == 'true') {
- $data['data']['EGA'] = [];
- $data['data']['EGA']['username'] = $postData['username']; // Modify this
- $data['data']['EGA']['password'] = $postData['password']; // Modify this
-
- $data['data']['EGA']['_id'] = $postData['_id'];
-
+function handleEgaAccount($action, $userId, $postData)
+{
+ if ($action === "update") {
+ try {
+ $egaAuthToken = getEgaAuthToken($postData['username'], $postData['password']);
+ $_SESSION['User']['EGA']['token'] = $egaAuthToken;
+ } catch (Exception $e) {
+ error_log("Could not connect to EGA: " . $e->getMessage());
+ $_SESSION['errorData']['Error'][] = "Could not connect to EGA. Please check your credentials.";
+ redirect($_SERVER['HTTP_REFERER']);
}
+ }
- } elseif ($action === "update") {
- $accessToken = json_decode($_SESSION['User']['JWT'], true)["access_token"];
- // Add logic for handling MN account and uploading credentials to Vault for "update" action
-
-
- if (!empty($postData['username']) && !empty($postData['password'])) {
- $data['data']['EGA'] = [];
- $data['data']['EGA']['username'] = $postData['username']; // Modify this
- $data['data']['EGA']['password'] = $postData['password']; // Modify this
-
-
- $data['data']['EGA']['_id'] = $postData['_id'];
- } else {
- // Handle the case where app_id or app_secret is empty
- $_SESSION['errorData']['Error'][] = "Please provide both username and password.";
- $_SESSION['formData'] = $postData;
+ $data = [];
+ if ($action === "update") {
+ if (empty($postData['username']) || empty($postData['password'])) {
+ $_SESSION['errorData']['Error'][] = "Please provide username and password.";
redirect($_SERVER['HTTP_REFERER']);
+ } else {
+ $data['data']['EGA'] = [];
+ $data['data']['EGA']['username'] = $postData['username'];
+ $data['data']['EGA']['password'] = $postData['password'];
+ $data['data']['EGA']['privateKey'] = $postData['privateKey'];
+ $data['data']['EGA']['_id'] = $userId;
}
-
} elseif ($action === "delete") {
- // Reset data for "delete" action
- $data = [];
- $_SESSION['errorData']['Info'][] = "Credentials for user erased, please provide new ones.";
+ clearLinkedAccount("EGA");
+ redirect($_SERVER['HTTP_REFERER']);
} else {
handleInvalidAction();
}
- //var_dump($_SESSION['User']['Vault']['vaultKey']);
-
- //var_dump($data);
- //var_dump($accessToken);
-
-
+ $accessToken = json_decode($_SESSION['User']['JWT'], true)["access_token"];
$vaultClient = new VaultClient(
$GLOBALS['vaultUrl'],
- $_SESSION['User']['Vault']['vaultToken'],
+ $_SESSION['userVaultInfo']['vaultToken'],
$accessToken,
- $_SESSION['User']['Vault']['vaultRolename'],
+ $_SESSION['userVaultInfo']['vaultRolename'],
$postData['username']
);
- //var_dump($data);
$key = $vaultClient->uploadKeystoVault($data);
-
- //var_dump($key);
- // Update user data with vault key
- $_SESSION['User']['Vault']['vaultKey'] = $key;
- updateUser($_SESSION['User']);
+ $_SESSION['userVaultInfo']['vaultKey'] = $key;
if (!$key) {
$_SESSION['errorData']['Info'][] = "";
$_SESSION['errorData']['Error'][] = "Failed to link EGA account";
- $_SESSION['formData'] = $postData;
+ error_log("Failed to link EGA account");
+ error_log("Vault key: " . $key);
redirect($_SERVER['HTTP_REFERER']);
}
@@ -551,76 +388,32 @@ function handleEGAAccount($action, $postData) {
}
-function handleInvalidData() {
- $_SESSION['errorData']['Error'][] = "Not receiving expected fields. Please submit the data again.";
- $_SESSION['formData'] = $postData;
- redirect($_SERVER['HTTP_REFERER']);
+function clearLinkedAccount($account)
+{
+ // TODO: To be implemented
+ $_SESSION['errorData']['Info'][] = "Credentials for user erased, please provide new ones.";
}
-function handleResult($result) {
- if (!$result) {
- $_SESSION['errorData']['Error'][] = "Failed to perform the requested action.";
- $_SESSION['formData'] = $postData;
- redirect($_SERVER['HTTP_REFERER']);
- }
- $_SESSION['errorData']['Info'][] = "Action successfully completed.";
- redirect($GLOBALS['BASEURL'] . "user/usrProfile.php#tab_1_4");
-}
-
-function handleInvalidAction() {
- $_SESSION['errorData']['Error'][] = "Invalid action for the specified account type.";
- redirect($_SERVER['HTTP_REFERER']);
-}
-
-
-function generate_RSA_keys($username, $server, $account) {
- $config = array(
- "digest_alg" => "sha512",
- "private_key_bits" => 2048,
- "private_key_type" => OPENSSL_KEYTYPE_RSA,
- );
-
- // Generate the key pair
- $res = openssl_pkey_new($config);
-
- // Extract the private key
- openssl_pkey_export($res, $privateKey);
- $formattedPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\n";
- $formattedPrivateKey .= wordwrap($privateKey, 64, "\n", true);
- $formattedPrivateKey .= "\n-----END RSA PRIVATE KEY-----";
-
- // Extract the public key
- $publicKeyDetails = openssl_pkey_get_details($res);
- $publicKey = $publicKeyDetails['key'];
- $publicKey = str_replace(["-----BEGIN PUBLIC KEY-----", "-----END PUBLIC KEY-----", "\n", "\r"], '', $publicKey);
- $publicKey = "ssh-rsa " . trim($publicKey) . " " . $username . "@" . $server;
-
- // Save or use the keys as needed
- // For example, you might want to save them in your database
-// var_dump($privateKey);
-// var_dump($publicKey);
-
- // Return the keys along with the account
- return array(
- 'account' => $account,
- 'private_key' => $formattedPrivateKey,
- 'public_key' => $publicKey,
- );
+function handleInvalidAction()
+{
+ $_SESSION['errorData']['Error'][] = "Action not recognized.";
+ redirect($_SERVER['HTTP_REFERER']);
}
-function generateSSHKeyPair($username) {
+function generateSSHKeyPair($username)
+{
// Temporary directory to store key files
$tempDir = sys_get_temp_dir();
$privateKeyPath = $tempDir . '/id_ed25519_' . $username;
$publicKeyPath = $tempDir . '/id_ed25519_' . $username . '.pub';
-
+
// Generate the key pair using ssh-keygen and store it temporarily
shell_exec("ssh-keygen -t ed25519 -f " . escapeshellarg($privateKeyPath) . " -N ''");
- $privateKey = file_get_contents($privateKeyPath);
- $publicKey = file_get_contents($publicKeyPath);
+ $privateKey = file_get_contents($privateKeyPath);
+ $publicKey = file_get_contents($publicKeyPath);
// Clean up the temporary key files
unlink($privateKeyPath);
@@ -633,87 +426,29 @@ function generateSSHKeyPair($username) {
}
-function registerEgaPubKey($pubKey, $username, $vaultClient, $vaultKey) {
- $egaTempKeysEndpoint = $GLOBALS['EGA_EPHEMERAL_KEYS_ENDPOINT'] . "/$username";
- $validFor = "1 hour";
+function generateSSHButtons()
+{
+ // Check if $GLOBALS['sitesCol'] is set
+ if (isset($GLOBALS['sitesCol'])) {
+ // Fetch the documents that have "SSH" in the "accessible_via" array
+ $documents = $GLOBALS['sitesCol']->find([
+ 'launcher.accessible_via' => 'SSH' // Filter condition
+ ]);
- $data = json_encode([
- "pubkey" => $pubKey,
- "valid_for" => $validFor
- ]);
+ // Initialize HTML output and results flag
+ $buttonsHTML = '';
+ $documentsFound = false;
- // Initialize cURL session
- $ch = curl_init();
+ // Iterate through the documents
+ foreach ($documents as $document) {
+ $documentsFound = true;
- // Set cURL options
- curl_setopt($ch, CURLOPT_URL, $egaTempKeysEndpoint);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Content-Type: application/json'
- ]);
+ // Prepare the data to fill up the buttons
+ $siteId = (string) $document['_id'];
+ $siteSigla = (string) $document['sigla'];
-
- $vaultUrl = $GLOBALS['vaultUrl'];
- $credentials = $vaultClient->retrieveDatafromVault('ega', $vaultKey, $vaultUrl, 'secret/mysecret/data/', $GLOBALS['bscEgaCredentialsFilename']);
- if (is_null($credentials)) {
- $_SESSION['errorData']['Error'][] = "Internal error. Failed to retrieve BSC-EGA credentials.";
- return false;
- }
-
- $egaKeyEndpointUser = $credentials['username'];
- $egaKeyEndpointPassword = $credentials['password'];
- curl_setopt($ch, CURLOPT_USERPWD, "$egaKeyEndpointUser:$egaKeyEndpointPassword");
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
-
- $response = curl_exec($ch);
-
- if (curl_errno($ch)) {
- $error_msg = curl_error($ch);
- }
-
- curl_close($ch);
-
- if (isset($error_msg)) {
- error_log("Error message: " . $error_msg);
- $_SESSION['errorData']['Error'][] = "Error: $error_msg";
- return false;
- }
-
- $responseData = json_decode($response, true);
-
- if (isset($responseData['result']) && $responseData['result'] === 'ok') {
- return true;
- } else {
- $_SESSION['errorData']['Error'][] = "Request failed. Response: " . $response;
- return false;
- }
-}
-
-function generateSSHButtons() {
- // Check if $GLOBALS['sitesCol'] is set
- if (isset($GLOBALS['sitesCol'])) {
- // Fetch the documents that have "SSH" in the "accessible_via" array
- $documents = $GLOBALS['sitesCol']->find([
- 'launcher.accessible_via' => 'SSH' // Filter condition
- ]);
-
- // Initialize HTML output and results flag
- $buttonsHTML = '';
- $hayResults = false;
-
- // Iterate through the documents
- foreach ($documents as $document) {
- $hayResults = true;
-
- // Prepare the data to fill up the buttons
- $siteName = htmlspecialchars($document['name']);
- $siteId = (string) $document['_id'];
- //$siteSigla = isset($document['sigla']) ? htmlspecialchars($document['_id']) : 'N/A';
- $siteSigla = (string) $document['sigla'];
-
- // Create the button for each site
- $buttonsHTML .= '
+ // Create the button for each site
+ $buttonsHTML .= '
';
- }
-
- // Check if no documents were found
- if (!$hayResults) {
- $_SESSION['errorData']['Error'][] = "No SSH-accessible sites found.";
- $buttonsHTML = '
No HPC accounts found with SSH access.
';
- }
-
- return $buttonsHTML;
- } else {
- // Log if $GLOBALS['sitesCol'] is not set
- $_SESSION['errorData']['Error'][] = "Sites collection is not available.";
- return '
Sites collection is not available.
';
- }
-}
-
-
-function getSiteDetails($siteId) {
- // Check if the siteId is valid
- if (isset($siteId)) {
- // Fetch site details from the database
- $site = $GLOBALS['sitesCol']->findOne(['_id' =>$siteId]);
-
- // If the site is found, return the necessary details
- if ($site) {
- $siteName = htmlspecialchars($site['name']);
- $siteAcronym = isset($site['sigla']) ? htmlspecialchars($site['sigla']) : 'N/A';
- return ['siteName' => $siteName, 'siteAcronym' => $siteAcronym];
- }
- }
- // Return default values if site not found
- return ['siteName' => 'Unknown Site', 'siteAcronym' => 'N/A'];
-}
-
+ }
-function getSiteCredentials($siteId) {
- if (isset($siteId)) {
- // Fetch site details from the database
- $site = $GLOBALS['sitesCol']->findOne(['_id' =>$siteId]);
+ // Check if no documents were found
+ if (!$documentsFound) {
+ $_SESSION['errorData']['Error'][] = "No SSH-accessible sites found.";
+ $buttonsHTML = '
No HPC accounts found with SSH access.
';
+ }
- if ($site) {
- // Return the credentials if they exist, else return default empty values
- $credentials = isset($site['launcher']['access_credentials']) ? $site['launcher']['access_credentials'] : null;
- return $credentials;
- }
- }
- return null;
+ return $buttonsHTML;
+ } else {
+ // Log if $GLOBALS['sitesCol'] is not set
+ $_SESSION['errorData']['Error'][] = "Sites collection is not available.";
+ return '
Sites collection is not available.
';
+ }
}
-
-
-?>
diff --git a/front_end/openVRE/public/phplib/mongoDMP.inc.php b/front_end/openVRE/public/phplib/mongoDMP.inc.php
index 4e74ec93..bd20d3da 100644
--- a/front_end/openVRE/public/phplib/mongoDMP.inc.php
+++ b/front_end/openVRE/public/phplib/mongoDMP.inc.php
@@ -7,8 +7,8 @@ function DMP_http($method,$service,$data=false){
$info = array();
$url_base = $GLOBALS['DMPserver_domain'].":".$GLOBALS['DMPserver_port'].$GLOBALS['DMPserver_address'];
- $headers = array("Content-Type: application/json", "Authorization: Bearer ".$_SESSION['User']['token']);
- print "HEADER : -H \"Content-Type: application/json\" -H \"Authorization: Bearer ".$_SESSION['User']['token']."\"\n";
+ $headers = array("Content-Type: application/json", "Authorization: Bearer ".$_SESSION['userToken']);
+ print "HEADER : -H \"Content-Type: application/json\" -H \"Authorization: Bearer ".$_SESSION['userToken']."\"\n";
$url = $url_base."/".$service;
switch ($method){
diff --git a/front_end/openVRE/public/phplib/obj_storage.inc.php b/front_end/openVRE/public/phplib/obj_storage.inc.php
index 105ce27a..fb53c450 100644
--- a/front_end/openVRE/public/phplib/obj_storage.inc.php
+++ b/front_end/openVRE/public/phplib/obj_storage.inc.php
@@ -3,7 +3,7 @@
function getOpenstackUser($vaultUrl, $vaultToken, $accessToken, $vaultRolename, $username) {
$vaultClient = new VaultClient($vaultUrl, $vaultToken, $accessToken, $vaultRolename, $username);
- $vaultKey = $_SESSION['User']['Vault']['vaultKey'];
+ $vaultKey = $_SESSION['userVaultInfo']['vaultKey'];
$credentials = $vaultClient->retrieveDatafromVault('Swift', $vaultKey, $vaultUrl, 'secret/mysecret/data/', $_SESSION['User']['_id'] . '_credentials.txt');
if ($credentials) {
@@ -26,7 +26,7 @@ function getOpenstackUser($vaultUrl, $vaultToken, $accessToken, $vaultRolename,
function getSwiftClient($vaultUrl, $vaultToken, $accessToken, $vaultRolename, $username) {
$vaultClient = new VaultClient($vaultUrl, $vaultToken, $accessToken, $vaultRolename, $username);
- $vaultKey = $_SESSION['User']['Vault']['vaultKey'];
+ $vaultKey = $_SESSION['userVaultInfo']['vaultKey'];
$credentials = $vaultClient->retrieveDatafromVault('Swift', $vaultKey, $vaultUrl, 'secret/mysecret/data/', $_SESSION['User']['_id'] . '_credentials.txt');
error_log($vaultKey, $credentials);
@@ -50,7 +50,7 @@ function getSwiftClient($vaultUrl, $vaultToken, $accessToken, $vaultRolename, $u
function getSSHClient($vaultUrl, $vaultToken, $accessToken, $vaultRolename, $username, $remote_dir, $siteId) {
$vaultClient = new VaultClient($vaultUrl, $vaultToken, $accessToken, $vaultRolename, $username);
- $vaultKey = $_SESSION['User']['Vault']['vaultKey'];
+ $vaultKey = $_SESSION['userVaultInfo']['vaultKey'];
$credentials = $vaultClient->retrieveDatafromVault('SSH', $vaultKey, $vaultUrl, 'secret/mysecret/data/', $_SESSION['User']['_id'] . '_credentials.txt');
// error_log($vaultKey, $credentials);
if ($credentials) {
diff --git a/front_end/openVRE/public/phplib/projects.inc.php b/front_end/openVRE/public/phplib/projects.inc.php
index 3a304699..71ed5819 100644
--- a/front_end/openVRE/public/phplib/projects.inc.php
+++ b/front_end/openVRE/public/phplib/projects.inc.php
@@ -1,16 +1,17 @@
$metadataPath ";
return 0;
@@ -246,7 +230,7 @@ function setUserWorkSpace_sampleData($sampleName, $dataDir, $verbose = TRUE)
// TODO: check if it is necessary
// looking for files in the folder
- $sampleDataPath = $GLOBALS['sampleData'] . "/" . $sampleData['sample_path'] . "/" . $metadata['file_path'];
+ $sampleDataPath = $GLOBALS['sampleDataPath'] . "/" . $sampleData['sample_path'] . "/" . $metadata['file_path'];
$metaFilePath = "$sampleDataPath/.sample_metadata.json";
if (!is_file($metaFilePath)) {
@@ -279,7 +263,7 @@ function setUserWorkSpace_sampleData($sampleName, $dataDir, $verbose = TRUE)
function save_fromSampleDataMetadata($metadata, $dataDir, $sampleName, $type, $verbose = TRUE)
{
$sampleData = getSampleData($sampleName);
- $sampleDataPath = $GLOBALS['sampleData'] . "/" . $sampleData['sample_path'] . "/" . $metadata['file_path'];
+ $sampleDataPath = $GLOBALS['sampleDataPath'] . "/" . $sampleData['sample_path'] . "/" . $metadata['file_path'];
$dataDirPath = $GLOBALS['dataDir'] . "/$dataDir";
$userDataPath = $dataDirPath . "/" . $metadata['file_path'];
@@ -640,13 +624,7 @@ function printLastJobs($filesAll = array())
if (preg_match('/\/\./', $r['_id']))
continue;
if (isset($r['pending'])) {
- /*if(basename($r['path']) != "repository") {
- print parseTemplate(formatData($r), getTemplate('/LastJobsworkspace/LJ_folderPending.htm'));
- $wehavejobs = true;
- }*/
} elseif ((basename($r['path']) == "uploads") || (basename($r['path']) == "repository")) {
- //$wehavejobs = false;
- //print parseTemplate(formatData($r), getTemplate('/TreeTblworkspace/TR_folder_uploads.htm'));
} elseif (!strpos($r['files'][0], "dummy")) {
print parseTemplate(formatData($r), getTemplate('/LastJobsworkspace/LJ_folder.htm'));
$wehavejobs = true;
@@ -673,15 +651,10 @@ function printLastJobs($filesAll = array())
function getToolsByDT($data_type, $status = 1)
{
-
$tl = $GLOBALS['toolsCol']->find(array('external' => true, 'status' => array('$in' => [$status, 3])));
-
- if ($_SESSION['User']['Type'] == 1) {
-
+ if ($_SESSION['User']['Type'] == UserType::ToolDev->value) {
$tools_list = iterator_to_array($tl, false);
-
foreach ($tools_list as $key => $tool) {
-
if ($tool["status"] == 3 && !in_array($tool["_id"], $_SESSION['User']["ToolsDev"])) {
unset($tools_list[$key]);
}
@@ -871,7 +844,7 @@ function formatData($data)
$data['log_file'] = str_replace($GLOBALS['dataDir'] . "/", "", $data['log_file']);
}
$viewLog_state = "enabled";
- if ($data['pending'] == "HOLD" || $data['pending'] == "PENDING") {
+ if (isset($data['pending']) && ($data['pending'] == "HOLD" || $data['pending'] == "PENDING")) {
$viewLog_state = 'disabled';
} elseif (!is_file($GLOBALS['dataDir'] . "/" . $data['log_file']) && !is_link($GLOBALS['dataDir'] . "/" . $data['log_file'])) {
$viewLog_state = 'disabled';
@@ -1128,7 +1101,6 @@ function updatePendingFiles($sessionId, $singleJob = array())
// TODO: PMES will redirect log info to log_file. Now, info extracted from $jobProcess
updateLogFromJobInfo($job['log_file'], $pid, $job['launcher']);
-
//job keeps running: maintain original job data
if (count($jobProcess)) {
//keep monitoring
@@ -1945,14 +1917,15 @@ function downloadFile($rfn)
exit(0);
}
+
function refresh_token($force = false)
{
- if (!$_SESSION['User']['Token']['access_token']) {
+ if (!$_SESSION['userToken']['access_token']) {
ob_clean();
header('Location: ' . $GLOBALS['BASEURL'] . '/htmlib/errordb.php?msg=MuG Authentification Session Expired.
Login again');
}
- $existingTokenO = new AccessToken($_SESSION['User']['Token']);
+ $existingTokenO = new AccessToken($_SESSION['userToken']);
//$provider = new MuG_Oauth2Provider\MuG_Oauth2Provider(['redirectUri'=> 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF']]);
$provider = new MuG_Oauth2Provider\MuG_Oauth2Provider(['redirectUri' => $GLOBALS['URL'] . $_SERVER['PHP_SELF']]);
@@ -1971,11 +1944,10 @@ function refresh_token($force = false)
// save in mongo
$user = $_SESSION['User'];
- $user['Token'] = $newToken;
updateUser($user);
// load new token in session
- $_SESSION['User']['Token'] = $newToken;
+ $_SESSION['userToken'] = $newToken;
return true;
} else {
$_SESSION['errorData']['Warning'][] = "Access token not expired yet.
Force refresh";
@@ -1987,50 +1959,29 @@ function refresh_token($force = false)
function refresh_vault_token($force = false)
{
-
- if (!$_SESSION['User']['Vault']['vaultKey']) {
+ if (!$_SESSION['userVaultInfo']['vaultKey']) {
ob_clean();
header('Location: ' . $GLOBALS['BASEURL'] . '/htmlib/errordb.php?msg=Vault Authentification Session Expired.
Login again');
}
- //echo "refresh_vault_token";
- //echo $_SESSION['User']['Vault']['vaultKey'];
-
- $existingToken = $_SESSION['User']['Vault']['vaultKey'];
-
- //$provider = new MuG_Oauth2Provider\MuG_Oauth2Provider(['redirectUri'=> 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF']]);
- //$provider = new MuG_Oauth2Provider\MuG_Oauth2Provider(['redirectUri'=> $GLOBALS['URL'] . $_SERVER['PHP_SELF']]);
-
+ $existingToken = $_SESSION['userVaultInfo']['vaultKey'];
//add them to mongo
- $provider = new VaultClient($_SESSION['User']['Vault']['vaultUrl'], $_SESSION['User']['Vault']['vaultToken'], $_SESSION['User']['Token']['access_token'], $_SESSION['User']['Vault']['vaultRole'], $_POST['username']);
+ $provider = new VaultClient($_SESSION['userVaultInfo']['vaultUrl'], $_SESSION['userVaultInfo']['vaultToken'], $_SESSION['userToken']['access_token'], $_SESSION['userVaultInfo']['vaultRole'], $_POST['username']);
- $expirationTime = $provider->getTokenExpirationTime($_SESSION['User']['Vault']['vaultUrl'], $existingToken);
- //echo "refresh_vault_token_1";
- //echo $expirationTime;
-
- //expiration time can be or the timestamp or false:
- //if ($force || $provider->isTokenExpired($_SESSION['User']['Vault']['vaultUrl'], $existingToken)) {
+ $expirationTime = $provider->getTokenExpirationTime($_SESSION['userVaultInfo']['vaultUrl'], $existingToken);
if ($force || ($expirationTime !== false)) {
try {
- //echo "refresh_vault_token_2";
- $newToken = $provider->renewVaultToken($_SESSION['User']['Vault']['vaultUrl'], $existingToken);
- //echo "refresh_vault_token_3";
- //echo $newToken;
+ $newToken = $provider->renewVaultToken($_SESSION['userVaultInfo']['vaultUrl'], $existingToken);
if ($newToken) {
$newToken = json_decode($newToken, true);
- $user = $_SESSION['User'];
- $_SESSION['User']['Vault']['vaultKey'] = $newToken;
- $tokenTime = $provider->getTokenExpirationTime($_SESSION['User']['Vault']['vaultUrl'], $user['Vault']['vaultKey']);
- //echo "refresh_vault_token_4";
- //echo $tokenTime;
+ $_SESSION['userVaultInfo']['vaultKey'] = $newToken;
+ $tokenTime = $provider->getTokenExpirationTime($_SESSION['userVaultInfo']['vaultUrl'], $_SESSION['userVaultInfo']['vaultKey']);
if ($tokenTime !== false) {
- $user['Vault']['expires_in'] = $tokenTime;
- //echo "Updated";
+ $_SESSION['userVaultInfo']['expires_in'] = $tokenTime;
}
- updateUser($user);
- $_SESSION['User']['Vault']['vaultKey'] = $newToken;
- $_SESSION['User']['Vault']['expires_in'] = $tokenTime;
- //updateUser($user);
+ updateUser($_SESSION['User']);
+ $_SESSION['userVaultInfo']['vaultKey'] = $newToken;
+ $_SESSION['userVaultInfo']['expires_in'] = $tokenTime;
return true;
}
} catch (Exception $e) {
@@ -2195,6 +2146,7 @@ function resolvePath_toLocalAbsolutePath($path, $job)
} elseif (preg_match('/^' . $job['execution'] . '/', $path)) {
//$rfn = $GLOBALS['dataDir'].$_SESSION['User']['id']."/".$_SESSION['User']['activeProject']."/".$path;
$rfn = dirname($job["output_dir"]) . "/" . $path;
+
// file_path is relative to root directory (userid/prj/run/file)
} elseif (preg_match('/^' . $_SESSION['User']['id'] . '/', $path)) {
$rfn = $GLOBALS['dataDir'] . "/" . $path;
diff --git a/front_end/openVRE/public/phplib/templates.inc.php b/front_end/openVRE/public/phplib/templates.inc.php
index 7ac1a205..50a6b5be 100644
--- a/front_end/openVRE/public/phplib/templates.inc.php
+++ b/front_end/openVRE/public/phplib/templates.inc.php
@@ -35,9 +35,12 @@ function parseTemplate($f, $txt, $indirFields = '', $dateFields = '', $incRec =
}
}
foreach (array_keys($f) as $k){
- if (is_array($f[$k]))
+ if (is_array($f[$k])) {
continue;
- $txt = str_replace("##$k##", $f[$k], $txt);
+ }
+
+ $replace = $f[$k] ?? "";
+ $txt = str_replace("##$k##", $replace, $txt);
}
if (!$recursive)
$txt = preg_replace("/##([^#]*)##/", "", $txt);
diff --git a/front_end/openVRE/public/phplib/tools.list.inc.php b/front_end/openVRE/public/phplib/tools.list.inc.php
index 8c6253eb..bda4de22 100644
--- a/front_end/openVRE/public/phplib/tools.list.inc.php
+++ b/front_end/openVRE/public/phplib/tools.list.inc.php
@@ -4,69 +4,60 @@
// list tools
-function getTools_List($status = 1) {
- if ($_SESSION['User']['Type'] == 3){
- $tools = $GLOBALS['toolsCol']->find(array('external' => true, 'status' => $status, 'owner.license' => array('$ne' => "free_for_academics")), array('name' => 1, 'title' => 1, 'short_description' => 1, 'keywords' => 1),array('title' => 1));
- } elseif($_SESSION['User']['Type'] == 0 || $_SESSION['User']['Type'] == 1) {
- $tools = $GLOBALS['toolsCol']->find(array('external' => true, 'status' => $status), array('name' => 1, 'title' => 1, 'short_description' => 1, 'keywords' => 1, 'status' => 1),array('title' => 1));
- } else {
- $tools = $GLOBALS['toolsCol']->find(array('external' => true, 'status' => $status), array('name' => 1, 'title' => 1, 'short_description' => 1, 'keywords' => 1),array('title' => 1));
- }
-
- if($_SESSION['User']['Type'] == 1) {
-
- $tools_list = iterator_to_array($tools);
-
- foreach($tools_list as $key => $tool) {
-
- if($tool["status"] == 3 && !in_array($tool["_id"], $_SESSION['User']["ToolsDev"])) {
- unset($tools_list[$key]);
- }
-
- }
-
- return $tools_list;
+function getTools_List($status = 1)
+{
+ if ($_SESSION['User']['Type'] == UserType::Guest->value) {
+ $tools = $GLOBALS['toolsCol']->find(array('external' => true, 'status' => $status, 'owner.license' => array('$ne' => "free_for_academics")), array('name' => 1, 'title' => 1, 'short_description' => 1, 'keywords' => 1), array('title' => 1));
+ } elseif ($_SESSION['User']['Type'] == UserType::Admin->value || $_SESSION['User']['Type'] == UserType::ToolDev->value) {
+ $tools = $GLOBALS['toolsCol']->find(array('external' => true, 'status' => $status), array('name' => 1, 'title' => 1, 'short_description' => 1, 'keywords' => 1, 'status' => 1), array('title' => 1));
+ } else {
+ $tools = $GLOBALS['toolsCol']->find(array('external' => true, 'status' => $status), array('name' => 1, 'title' => 1, 'short_description' => 1, 'keywords' => 1), array('title' => 1));
+ }
- } else {
- return iterator_to_array($tools);
- }
+ if ($_SESSION['User']['Type'] == UserType::ToolDev->value) {
+ $tools_list = iterator_to_array($tools);
+ foreach ($tools_list as $key => $tool) {
+ if ($tool["status"] == 3 && !in_array($tool["_id"], $_SESSION['User']["ToolsDev"])) {
+ unset($tools_list[$key]);
+ }
+ }
+ return $tools_list;
+ } else {
+ return iterator_to_array($tools);
+ }
}
// list tools
-function getTools_ListComplete($status = 1) {
- if ($_SESSION['User']['Type'] == 3){
- $tools = $GLOBALS['toolsCol']->find(array('external' => true, 'status' => $status, 'owner.license' => array('$ne' => "free_for_academics")), array(),array('title' => 1));
- }elseif($_SESSION['User']['Type'] == 0 || $_SESSION['User']['Type'] == 1) {
- $tools = $GLOBALS['toolsCol']->find(array('external' => true, 'status' => array('$ne' => 2)), array(),array('title' => 1));
- }else{
- $tools = $GLOBALS['toolsCol']->find(array('external' => true, 'status' => $status), array(),array('title' => 1));
- }
-
- if($_SESSION['User']['Type'] == 1) {
-
- $tools_list = iterator_to_array($tools);
-
- foreach($tools_list as $key => $tool) {
-
- if($tool["status"] == 3 && !in_array($tool["_id"], $_SESSION['User']["ToolsDev"])) {
- unset($tools_list[$key]);
- }
-
- }
-
- return $tools_list;
+function getTools_ListComplete($status = 1)
+{
+ if ($_SESSION['User']['Type'] == UserType::Guest->value) {
+ $tools = $GLOBALS['toolsCol']->find(array('external' => true, 'status' => $status, 'owner.license' => array('$ne' => "free_for_academics")), array(), array('title' => 1));
+ } elseif ($_SESSION['User']['Type'] == UserType::Admin->value || $_SESSION['User']['Type'] == UserType::ToolDev->value) {
+ $tools = $GLOBALS['toolsCol']->find(array('external' => true, 'status' => array('$ne' => 2)), array(), array('title' => 1));
+ } else {
+ $tools = $GLOBALS['toolsCol']->find(array('external' => true, 'status' => $status), array(), array('title' => 1));
+ }
- } else {
- return iterator_to_array($tools);
- }
+ if ($_SESSION['User']['Type'] == UserType::ToolDev->value) {
+ $tools_list = iterator_to_array($tools);
+ foreach ($tools_list as $key => $tool) {
+ if ($tool["status"] == 3 && !in_array($tool["_id"], $_SESSION['User']["ToolsDev"])) {
+ unset($tools_list[$key]);
+ }
+ }
+ return $tools_list;
+ } else {
+ return iterator_to_array($tools);
+ }
}
// list tools
-function getTool_fromId($toolId, $indexByName = 0) {
+function getTool_fromId($toolId, $indexByName = 0)
+{
$filterFields = [];
$tool = $GLOBALS['toolsCol']->findOne(['_id' => $toolId], $filterFields);
if (empty($tool)) {
@@ -88,7 +79,6 @@ function getTool_fromId($toolId, $indexByName = 0) {
if (!$shouldReindex) {
$toolIndexed[$attribute] = $value;
}
-
} else {
$toolIndexed[$attribute] = $value;
}
@@ -102,152 +92,158 @@ function getTool_fromId($toolId, $indexByName = 0) {
// list visualizers
-function getVisualizer_fromId($toolId,$indexByName=0) {
- $filterfields=array();
- $tool = $GLOBALS['visualizersCol']->findOne(array('_id' => $toolId)/*, $filterfields*/);
-
- if (empty($tool))
- return 0;
-
- if ($indexByName){
- $toolIndexed=Array();
- foreach ($tool as $attribute => $value){
- if (is_array($value)){
- $t=0;
- foreach ($value as $v){
- if (isset($v['name'])){
- $t=1;
- $toolIndexed[$attribute][$v['name']]=$v;
+function getVisualizer_fromId($toolId, $indexByName = 0)
+{
+ $filterfields = array();
+ $tool = $GLOBALS['visualizersCol']->findOne(array('_id' => $toolId)/*, $filterfields*/);
+
+ if (empty($tool))
+ return 0;
+
+ if ($indexByName) {
+ $toolIndexed = array();
+ foreach ($tool as $attribute => $value) {
+ if (is_array($value)) {
+ $t = 0;
+ foreach ($value as $v) {
+ if (isset($v['name'])) {
+ $t = 1;
+ $toolIndexed[$attribute][$v['name']] = $v;
+ }
+ }
+ if (!$t) {
+ $toolIndexed[$attribute] = $value;
}
- }
- if (!$t){
- $toolIndexed[$attribute]=$value;
- }
- }else{
- $toolIndexed[$attribute]=$value;
+ } else {
+ $toolIndexed[$attribute] = $value;
}
- }
+ }
$tool = $toolIndexed;
- }
+ }
return $tool;
-
-
}
// get Tool under development
-function getToolDev_fromId($toolId,$indexByName=0) {
- $tool = $GLOBALS['toolsDevMetaCol']->findOne(array('_id' => $toolId));
-
- if (empty($tool))
- return 0;
-
- if ($indexByName){
- if ($tool["step1"]["tool_io"]){
- $toolIndexed=Array();
- foreach ($tool['step1']['tool_io'] as $attribute => $value){
- if (is_array($value)){
- $t=0;
- foreach ($value as $v){
- if (isset($v['name'])){
- $t=1;
- $toolIndexed[$attribute][$v['name']]=$v;
- }
- }
- if (!$t){
- $toolIndexed[$attribute]=$value;
- }
- }else{
- $toolIndexed[$attribute]=$value;
- }
- }
- $tool["step1"]["tool_io"] = $toolIndexed;
- }
- if ($tool["step3"]["tool_spec"]){
- $toolIndexed=Array();
- foreach ($tool['step3']['tool_spec'] as $attribute => $value){
- if (is_array($value)){
- $t=0;
- foreach ($value as $v){
- if (isset($v['name'])){
- $t=1;
- $toolIndexed[$attribute][$v['name']]=$v;
- }
- }
- if (!$t){
- $toolIndexed[$attribute]=$value;
- }
- }else{
- $toolIndexed[$attribute]=$value;
- }
- }
- $tool["step3"]["tool_spec"] = $toolIndexed;
- }
- }
+function getToolDev_fromId($toolId, $indexByName = 0)
+{
+ $tool = $GLOBALS['toolsDevMetaCol']->findOne(array('_id' => $toolId));
+
+ if (empty($tool))
+ return 0;
+
+ if ($indexByName) {
+ if ($tool["step1"]["tool_io"]) {
+ $toolIndexed = array();
+ foreach ($tool['step1']['tool_io'] as $attribute => $value) {
+ if (is_array($value)) {
+ $t = 0;
+ foreach ($value as $v) {
+ if (isset($v['name'])) {
+ $t = 1;
+ $toolIndexed[$attribute][$v['name']] = $v;
+ }
+ }
+ if (!$t) {
+ $toolIndexed[$attribute] = $value;
+ }
+ } else {
+ $toolIndexed[$attribute] = $value;
+ }
+ }
+ $tool["step1"]["tool_io"] = $toolIndexed;
+ }
+ if ($tool["step3"]["tool_spec"]) {
+ $toolIndexed = array();
+ foreach ($tool['step3']['tool_spec'] as $attribute => $value) {
+ if (is_array($value)) {
+ $t = 0;
+ foreach ($value as $v) {
+ if (isset($v['name'])) {
+ $t = 1;
+ $toolIndexed[$attribute][$v['name']] = $v;
+ }
+ }
+ if (!$t) {
+ $toolIndexed[$attribute] = $value;
+ }
+ } else {
+ $toolIndexed[$attribute] = $value;
+ }
+ }
+ $tool["step3"]["tool_spec"] = $toolIndexed;
+ }
+ }
return $tool;
}
// delete Tool under development
-function deleteToolDev($toolId) {
- $tool = $GLOBALS['toolsDevMetaCol']->findOne(array('_id' => $toolId));
- if (!$tool){
- $_SESSION['errorData']['Warning'][]="Cannot delete tool '$toolId'. Entry not found.";
- return 1;
- }
- // Clean associated dev files
- $dev_dir = $GLOBALS['dataDir']."/".$_SESSION['User']['id']."/.dev/".$toolId;
- if (is_dir($dev_dir)){
- exec ("rm -r \"$dev_dir\" 2>&1",$output);
- if (error_get_last()){
- $_SESSION['errorData']['Error'][]="Cannot delete tool '$toolId'.";
- $_SESSION['errorData']['Error'][]=implode(" ",$output);
- return 0;
- }
- }
-
- // Delete from mongo
- $GLOBALS['toolsDevMetaCol']->deleteOne(array('_id'=> $toolId));
-
- $tool = $GLOBALS['toolsDevMetaCol']->findOne(array('_id' => $toolId));
- if ($tool){
- $_SESSION['errorData']['Error'][]="Cannot delete tool '$toolId' from DB. An error occurred.";
- return 0;
- }
- return 1;
+function deleteToolDev($toolId)
+{
+ $tool = $GLOBALS['toolsDevMetaCol']->findOne(array('_id' => $toolId));
+ if (!$tool) {
+ $_SESSION['errorData']['Warning'][] = "Cannot delete tool '$toolId'. Entry not found.";
+ return 1;
+ }
+ // Clean associated dev files
+ $dev_dir = $GLOBALS['dataDir'] . "/" . $_SESSION['User']['id'] . "/.dev/" . $toolId;
+ if (is_dir($dev_dir)) {
+ exec("rm -r \"$dev_dir\" 2>&1", $output);
+ if (error_get_last()) {
+ $_SESSION['errorData']['Error'][] = "Cannot delete tool '$toolId'.";
+ $_SESSION['errorData']['Error'][] = implode(" ", $output);
+ return 0;
+ }
+ }
+
+ // Delete from mongo
+ $GLOBALS['toolsDevMetaCol']->deleteOne(array('_id' => $toolId));
+
+ $tool = $GLOBALS['toolsDevMetaCol']->findOne(array('_id' => $toolId));
+ if ($tool) {
+ $_SESSION['errorData']['Error'][] = "Cannot delete tool '$toolId' from DB. An error occurred.";
+ return 0;
+ }
+ return 1;
}
// has tool custom visualizer
-function hasTool_custom_visualizer($toolId){
- $has_custom_visualizer = $GLOBALS['toolsCol']->findOne(array('_id' => $toolId,
- 'output_files' =>array('$elemMatch' => array("custom_visualizer"=>true) )),
- array('_id'=>1)
- );
+function hasTool_custom_visualizer($toolId)
+{
+ $has_custom_visualizer = $GLOBALS['toolsCol']->findOne(
+ array(
+ '_id' => $toolId,
+ 'output_files' => array('$elemMatch' => array("custom_visualizer" => true))
+ ),
+ array('_id' => 1)
+ );
return $has_custom_visualizer;
}
// launch tool - used for internal tools
-
-function launchToolInternal($toolId, $inputs = [], $args = [], $outs = [], $output_dir = "", $logName = ""){
- $tool = getTool_fromId($toolId, 1);
- if (empty($tool)) {
- $_SESSION['errorData']['Error'][] = "Tool internal not specified or not registered. Please, register '$toolId'";
- return 0;
- }
-
- if ($tool['external'] !== false) {
- $_SESSION['errorData']['Error'][] = "Selected tool ($toolId) expected to be Internal but specification states: {'external':false}";
- return 0;
- }
-
- // Set Tool job - tmp working dir
- $execution = 0; // internal tool do not create a execution folder
- $project = 0; // internal tool do not have an associated project
- $descrip = "Internal job execution of ".$tool['name'];
+
+function launchToolInternal($toolId, $inputs = [], $args = [], $outs = [], $output_dir = "", $logName = "")
+{
+ $tool = getTool_fromId($toolId, 1);
+ if (empty($tool)) {
+ $_SESSION['errorData']['Error'][] = "Tool internal not specified or not registered. Please, register '$toolId'";
+ return 0;
+ }
+
+ if ($tool['external'] !== false) {
+ $_SESSION['errorData']['Error'][] = "Selected tool ($toolId) expected to be Internal but specification states: {'external':false}";
+ return 0;
+ }
+
+ // Set Tool job - tmp working dir
+ $execution = 0; // internal tool do not create a execution folder
+ $project = 0; // internal tool do not have an associated project
+ $descrip = "Internal job execution of " . $tool['name'];
$jobMeta = new Tooljob($tool, $execution, $project, $descrip, $output_dir);
-
+
if (strlen($logName)) {
$jobMeta->setLog($logName);
}
@@ -257,30 +253,30 @@ function launchToolInternal($toolId, $inputs = [], $args = [], $outs = [], $outp
// Checking files locally
$files = []; // distinct file Objs to stage in
foreach ($inputs as $inName => $inIds) {
- foreach($inIds as $inId) {
+ foreach ($inIds as $inId) {
$file = getGSFile_fromId($inId);
if (!$file) {
$_SESSION['errorData']['Error'][] = "Input file $inId does not belong to current user or has been not properly registered. Stopping internal tool execution";
return 0;
}
-
+
$files[$file['_id']] = $file;
- }
+ }
}
$jobMeta->setInput_files($inputs, [], []);
if ($jobMeta->input_files == 0) {
$_SESSION['errorData']['Error'][] = "Internal tool execution has no input files defined";
- return 0;
+ return 0;
}
-
+
$args['working_dir'] = $jobMeta->working_dir;
- $jobMeta->setArguments($args, $tool);
+ $jobMeta->setArguments($args, $tool);
$jobId = $jobMeta->createWorking_dir();
if (!$jobId) {
$_SESSION['errorData']['Error'][] = "Cannot create tool temporal working dir";
- return 0;
+ return 0;
}
// Set outfiles metadata -- for register latter
@@ -288,7 +284,7 @@ function launchToolInternal($toolId, $inputs = [], $args = [], $outs = [], $outp
// Setting Command line. Adding parameters
$isExecutionPrepared = $jobMeta->prepareExecution($tool, $files);
- if($isExecutionPrepared == 0) {
+ if ($isExecutionPrepared == 0) {
return 0;
}
@@ -303,28 +299,29 @@ function launchToolInternal($toolId, $inputs = [], $args = [], $outs = [], $outp
}
-function parse_configFile_OBSOLETE($configFile){
+function parse_configFile_OBSOLETE($configFile)
+{
$configParsed = array();
// load config as json
$config = json_decode(file_get_contents($configFile));
// parse json
- $configParsed['input_files']= array();
- if ($config->input_files){
- foreach ($config->input_files as $input){
- if(!isset($configParsed['input_files'][$input->name]))
- $configParsed['input_files'][$input->name]=array();
- $input_fn = getAttr_fromGSFileId($input->value,'path');
+ $configParsed['input_files'] = array();
+ if ($config->input_files) {
+ foreach ($config->input_files as $input) {
+ if (!isset($configParsed['input_files'][$input->name]))
+ $configParsed['input_files'][$input->name] = array();
+ $input_fn = getAttr_fromGSFileId($input->value, 'path');
if ($input_fn)
- array_push($configParsed['input_files'][$input->name],str_replace($_SESSION['User']['id']."/","",$input_fn));
+ array_push($configParsed['input_files'][$input->name], str_replace($_SESSION['User']['id'] . "/", "", $input_fn));
else
- array_push($configParsed['input_files'][$input->name],$input->value);
+ array_push($configParsed['input_files'][$input->name], $input->value);
}
}
- $configParsed['arguments']= array();
- if ($config->arguments){
- foreach ($config->arguments as $arg){
+ $configParsed['arguments'] = array();
+ if ($config->arguments) {
+ foreach ($config->arguments as $arg) {
$configParsed['arguments'][$arg->name] = $arg->value;
}
}
@@ -332,81 +329,83 @@ function parse_configFile_OBSOLETE($configFile){
}
-function parse_submissionFile_SGE_OBSOLETE($rfn){
- $cmdsParsed = array();
-
- $cmds = preg_grep("/^\//",file($rfn));
- $cwd = str_replace("cd ","",join("",preg_grep("/^cd /", file($rfn))));
-
- $n=1;
- foreach ($cmds as $cmd){
-
- $cmdsParsed[$n]['cmdRaw'] = $cmd;
- $cmdsParsed[$n]['cwd'] = $cwd;
-
- $cmdsParsed[$n]['prgName'] = ""; # tool executable name for table title
- $cmdsParsed[$n]['params'] = array(); # paramName=>paramValue
-
- if (preg_match('/^#/',$cmd))
- continue;
- if (preg_match('/^(.[^ ]*) (.[^>]*)(\d*>*.*)$/',$cmd,$m)){
- $executable = ($m[1]? basename($m[1]):"No information" );
- $paramsStr = ($m[2]? $m[2]:"" );
- $log = ($m[3]? $m[3]:"" );
-
- // parse executable file
- $cmdsParsed[$n]['prgName'] = $executable;
-
- // parse cmd params
- foreach (explode("--",$paramsStr) as $p){
- trim($p);
- if (!$p)
- continue;
- list($k,$v) = explode(" ",$p);
- if (strlen($k)==0 && strlen($v)==0)
- continue;
- if (!$v)
- $v="";
- // if paramValue is a file, show only 'execution/filename'
- $v = str_replace($GLOBALS['dataDir']."/".$_SESSION['User']['id']."/","",$v);
-
- // HACK; when rfn comes from sample data, filenames in cmd do not contain the right userId. Cutting filepath using explode
- if (preg_match('/^\//',$v)){
- $execution = explode("/",$rfn);
- $v = $execution[count($execution)-2]."/".basename($v);
- }
- $cmdsParsed[$n]['params'][$k]=$v;
- }
- }
- $n++;
- }
- return $cmdsParsed;
+function parse_submissionFile_SGE_OBSOLETE($rfn)
+{
+ $cmdsParsed = array();
+
+ $cmds = preg_grep("/^\//", file($rfn));
+ $cwd = str_replace("cd ", "", join("", preg_grep("/^cd /", file($rfn))));
+
+ $n = 1;
+ foreach ($cmds as $cmd) {
+
+ $cmdsParsed[$n]['cmdRaw'] = $cmd;
+ $cmdsParsed[$n]['cwd'] = $cwd;
+
+ $cmdsParsed[$n]['prgName'] = ""; # tool executable name for table title
+ $cmdsParsed[$n]['params'] = array(); # paramName=>paramValue
+
+ if (preg_match('/^#/', $cmd))
+ continue;
+ if (preg_match('/^(.[^ ]*) (.[^>]*)(\d*>*.*)$/', $cmd, $m)) {
+ $executable = ($m[1] ? basename($m[1]) : "No information");
+ $paramsStr = ($m[2] ? $m[2] : "");
+ $log = ($m[3] ? $m[3] : "");
+
+ // parse executable file
+ $cmdsParsed[$n]['prgName'] = $executable;
+
+ // parse cmd params
+ foreach (explode("--", $paramsStr) as $p) {
+ trim($p);
+ if (!$p)
+ continue;
+ list($k, $v) = explode(" ", $p);
+ if (strlen($k) == 0 && strlen($v) == 0)
+ continue;
+ if (!$v)
+ $v = "";
+ // if paramValue is a file, show only 'execution/filename'
+ $v = str_replace($GLOBALS['dataDir'] . "/" . $_SESSION['User']['id'] . "/", "", $v);
+
+ // HACK; when rfn comes from sample data, filenames in cmd do not contain the right userId. Cutting filepath using explode
+ if (preg_match('/^\//', $v)) {
+ $execution = explode("/", $rfn);
+ $v = $execution[count($execution) - 2] . "/" . basename($v);
+ }
+ $cmdsParsed[$n]['params'][$k] = $v;
+ }
+ }
+ $n++;
+ }
+ return $cmdsParsed;
}
// list visualizers
-function getVisualizers_List($status = 1) {
-
+function getVisualizers_List($status = 1)
+{
+
$visualizers = $GLOBALS['visualizersCol']->find(array('external' => true, 'status' => $status), array('name' => 1, 'title' => 1, 'short_description' => 1, 'keywords' => 1), array('title' => 1));
- return iterator_to_array($visualizers);
-
+ return iterator_to_array($visualizers);
}
// list visualizers
-function getVisualizers_ListComplete($status = 1) {
-
+function getVisualizers_ListComplete($status = 1)
+{
+
$visualizers = $GLOBALS['visualizersCol']->find(array('external' => true, 'status' => $status), array(), array('title' => 1));
- return iterator_to_array($visualizers);
-
+ return iterator_to_array($visualizers);
}
// list file_types in use
-function getFileTypes_List() {
-
+function getFileTypes_List()
+{
+
$tls = $GLOBALS['toolsCol']->find(array('external' => true), array('name' => 1, 'input_files' => 1), array('name' => 1));
$tools = iterator_to_array($tls);
@@ -417,53 +416,50 @@ function getFileTypes_List() {
$i = 0;
- foreach($tools as $t) {
+ foreach ($tools as $t) {
- if(isset($t['input_files'])) {
+ if (isset($t['input_files'])) {
$filetypes[$i]['name'] = $t['name'];
$types = array();
- foreach($t['input_files'] as $if) array_push($types, implode($if['file_type']));
+ foreach ($t['input_files'] as $if) array_push($types, implode($if['file_type']));
$filetypes[$i]['file_types'] = $types;
- $i ++;
-
+ $i++;
}
-
}
return $filetypes;
-
}
// list a tool input file combination
-function getInputFilesCombinations($tool) {
+function getInputFilesCombinations($tool)
+{
$descriptions = [];
- foreach($tool["input_files_combinations"] as $t) {
+ foreach ($tool["input_files_combinations"] as $t) {
$descriptions[] = $t["description"];
-
}
- return implode("~", $descriptions);
-
+ return implode("~", $descriptions);
}
// list visualizers
-function getVisualizerTableList($file_types, $visualizer = null) {
+function getVisualizerTableList($file_types, $visualizer = null)
+{
$files_list = getGSFiles_filteredBy(array("format" => array('$in' => $file_types), "visible" => true));
error_log(print_r($file_types, true));
$list = [];
foreach ($files_list as $file) {
-
+
$path = getAttr_fromGSFileId($file["_id"], 'path');
$p = explode("/", $path);
@@ -478,141 +474,125 @@ function getVisualizerTableList($file_types, $visualizer = null) {
$html = '
';
-
- return $html;
-
-}
-
-
-// has tool custom visualizer
-function getToolDev_fromTool($toolId){
- $r = $GLOBALS['usersCol']->find(array('ToolsDev' =>array('$elemMatch' => array('$eq' => $toolId))),
- array ("_id" => 1));
+ $html .= '';
- if (empty($r))
- return Array();
-
- $r_arr = iterator_to_array($r);
- return array_keys($r_arr);
+ return $html;
}
+function getExecutionSitesForTool($toolId)
+{
+ // Retrieve tool document from the tools collection
+ $toolDocument = $GLOBALS['toolsCol']->findOne(['_id' => $toolId]);
-function getExecutionSitesForTool($toolId) {
- // Retrieve tool document from the tools collection
- $toolDocument = $GLOBALS['toolsCol']->findOne(['_id' => $toolId]);
-
- if (!$toolDocument) {
- return null;
- }
+ if (!$toolDocument) {
+ return null;
+ }
- $executionSitesData = $toolDocument['sites'];
- $executionSites = [];
- $launchers = [];
+ $executionSitesData = $toolDocument['sites'];
+ $executionSites = [];
+ $launchers = [];
- foreach ($executionSitesData as $siteData) {
- if ($siteData['status'] === 1) {
- $siteId = $siteData['site_id'];
+ foreach ($executionSitesData as $siteData) {
+ if ($siteData['status'] === 1) {
+ $siteId = $siteData['site_id'];
- //$_SESSION['errorData']['Error'][]="SiteId: {$siteId}";
+ //$_SESSION['errorData']['Error'][]="SiteId: {$siteId}";
- // Query the execution_sites collection to get details about the execution site
- // retrieve the document to check
- // $siteDocument = $GLOBALS['sitesCol']->findOne(['_id' => 'sites']);
- // per referenza: $tool = $GLOBALS['toolsCol']->findOne(array('_id' => $toolId), $filterfields);
- //$_SESSION['errorData']['Error'][]="Site Doc: " . print_r($siteDocument['site'], true);
- //$sites = $siteDocument['site'];
- //$siteDetails = $siteDocument['site'] ->findOne(['site_id' => $siteId]);
+ // Query the execution_sites collection to get details about the execution site
+ // retrieve the document to check
+ // $siteDocument = $GLOBALS['sitesCol']->findOne(['_id' => 'sites']);
+ // per referenza: $tool = $GLOBALS['toolsCol']->findOne(array('_id' => $toolId), $filterfields);
+ //$_SESSION['errorData']['Error'][]="Site Doc: " . print_r($siteDocument['site'], true);
+ //$sites = $siteDocument['site'];
+ //$siteDetails = $siteDocument['site'] ->findOne(['site_id' => $siteId]);
- if (isset($GLOBALS['sitesCol'])) {
- $matchingSite = null;
- foreach ($siteDocument['site'] as $site){
- if ($site['site_id'] == $siteId) {
- $matchingSite = $site;
- break;
+ if (isset($GLOBALS['sitesCol'])) {
+ $matchingSite = null;
+ foreach ($siteDocument['site'] as $site) {
+ if ($site['site_id'] == $siteId) {
+ $matchingSite = $site;
+ break;
+ }
}
- }
- if ($matchingSite) {
- $siteDetails = [
- 'site_id' => $matchingSite['site_id'],
- 'name' => $matchingSite['name'],
- 'launcher' => $matchingSite['launcher'],
- 'status' => $siteData['status'],
- ];
- $executionSites[] = $siteDetails;
- // $_SESSION['errorData']['Error'][] = "Site: " . print_r($siteDetails, true);
+ if ($matchingSite) {
+ $siteDetails = [
+ 'site_id' => $matchingSite['site_id'],
+ 'name' => $matchingSite['name'],
+ 'launcher' => $matchingSite['launcher'],
+ 'status' => $siteData['status'],
+ ];
+ $executionSites[] = $siteDetails;
+ // $_SESSION['errorData']['Error'][] = "Site: " . print_r($siteDetails, true);
+ } else {
+ $_SESSION['errorData']['Error'][] = "Site not found blabla for site ID: {$siteId}";
+ }
} else {
- $_SESSION['errorData']['Error'][]="Site not found blabla for site ID: {$siteId}";
+
+ $_SESSION['errorData']['Error'][] = "No 'site' field found in the document";
}
- } else {
-
- $_SESSION['errorData']['Error'][] = "No 'site' field found in the document";
+ }
}
- }
- }
-
- //$_SESSION['errorData']['Error'][] = "Site: " . print_r($siteDetails, true);
- //$_SESSION['errorData']['Error'][] = "Site: " . print_r($executionSites, true);
- return $executionSites;
+ //$_SESSION['errorData']['Error'][] = "Site: " . print_r($siteDetails, true);
+ //$_SESSION['errorData']['Error'][] = "Site: " . print_r($executionSites, true);
+ return $executionSites;
}
-function getSites_Info($toolId) {
+function getSites_Info($toolId)
+{
// Retrieve tool document from the tools collection
-// $filterfields=array();
+ // $filterfields=array();
$toolDocument = $GLOBALS['toolsCol']->findOne(['_id' => $toolId]);
//$_SESSION['errorData']['Error'][] = "Site: " . print_r($toolDocument, true);
if (!$toolDocument) {
@@ -627,7 +607,7 @@ function getSites_Info($toolId) {
if ($siteData['status'] === 1) {
$siteId = $siteData['site_id'];
//$_SESSION['errorData']['Error'][] = "site ID: {$siteId}";
- $filterfields=array();
+ $filterfields = array();
$siteDocument = $GLOBALS['sitesCol']->findOne(array('_id' => $siteId), $filterfields);
//$_SESSION['errorData']['Warning'][] = "Site Document: {$siteDocument}";
//echo ("Site Document: {$siteDocument}");
@@ -643,31 +623,27 @@ function getSites_Info($toolId) {
} else {
$_SESSION['errorData']['Error'][] = "Site not found jcjcj for site ID: {$siteId}";
}
-
}
-
}
//$_SESSION['errorData']['Error'][] = "Site: " . print_r($executionSites, true);
return $executionSites;
+}
+function getLauncherDetails($toolId)
+{
+ // Get the execution sites details
+ $executionSites = $this->getSites_Info($toolId);
-}
+ if (!$executionSites) {
+ return null;
+ }
-function getLauncherDetails($toolId) {
- // Get the execution sites details
- $executionSites = $this->getSites_Info($toolId);
-
- if (!$executionSites) {
- return null;
- }
-
- $launcherDetails = [];
- // Iterate through each site and extract only the launcher section
- foreach ($executionSites as $siteDetails) {
- if (isset($siteDetails['launcher'])) {
- $launcherDetails[] = $siteDetails['launcher'];
- }
- }
- return $launcherDetails;
+ $launcherDetails = [];
+ // Iterate through each site and extract only the launcher section
+ foreach ($executionSites as $siteDetails) {
+ if (isset($siteDetails['launcher'])) {
+ $launcherDetails[] = $siteDetails['launcher'];
+ }
+ }
+ return $launcherDetails;
}
-
diff --git a/front_end/openVRE/public/phplib/tools_filtering.inc.php b/front_end/openVRE/public/phplib/tools_filtering.inc.php
index 83881a82..04986c0e 100644
--- a/front_end/openVRE/public/phplib/tools_filtering.inc.php
+++ b/front_end/openVRE/public/phplib/tools_filtering.inc.php
@@ -6,28 +6,29 @@
// return datatype for a list of files
-function getFiles_DataTypes($fn) {
+function getFiles_DataTypes($fn)
+{
$fdt = $GLOBALS['filesMetaCol']->find(array('_id' => array('$in' => $fn)), array("_id" => false, "data_type" => true));
$a = array();
- foreach($fdt as $v) $a[] = $v["data_type"];
+ foreach ($fdt as $v) $a[] = $v["data_type"];
return $a;
-
}
// return datatype for a given toolId
-function getDT_byFT_DEPRECATED($id) {
+function getDT_byFT_DEPRECATED($id)
+{
$dt = $GLOBALS['toolsCol']->find(array("_id" => $id), array("input_files" => true));
$arr_dt = [];
- foreach($dt as $tool) {
- foreach($tool["input_files"] as $t) {
+ foreach ($dt as $tool) {
+ foreach ($tool["input_files"] as $t) {
$arr_dt = array_merge($arr_dt, $t["data_type"]);
}
}
@@ -45,7 +46,8 @@ function getDT_byFT_DEPRECATED($id) {
// return valid combination of input file datatypes for all tools
-function getTools_DataTypes() {
+function getTools_DataTypes()
+{
$dt = $GLOBALS['toolsCol']->find(array("external" => true), array("input_files_combinations_internal" => true));
@@ -53,9 +55,9 @@ function getTools_DataTypes() {
$c = 0;
- foreach($dt as $tool) {
+ foreach ($dt as $tool) {
- foreach($tool["input_files_combinations_internal"] as $combination) {
+ foreach ($tool["input_files_combinations_internal"] as $combination) {
// crear list 3 pels casos especÃfics?????
@@ -64,66 +66,58 @@ function getTools_DataTypes() {
$array[$c]["list2"] = array();
$array[$c]["list3"] = array();
- foreach($combination as $single_c) {
+ foreach ($combination as $single_c) {
- foreach($single_c as $k => $v) {
+ foreach ($single_c as $k => $v) {
// one item
- if($v == 1) $array[$c]["list1"][] = $k;
+ if ($v == 1) $array[$c]["list1"][] = $k;
// one or more (n mandatory)
- if($v == "+") {
+ if ($v == "+") {
$array[$c]["list1"][] = $k;
$array[$c]["list2"][] = $k;
}
// 0 or more (n non mandatory)
- if($v == "*") $array[$c]["list2"][] = $k;
+ if ($v == "*") $array[$c]["list2"][] = $k;
// special cases where no combinations internal are possible
- if($v == "-") $array[$c]["list3"][] = $k;
-
+ if ($v == "-") $array[$c]["list3"][] = $k;
}
-
}
- $c ++;
-
+ $c++;
}
-
}
return $array;
-
}
// return valid combination of input file datatypes for a given tool
-function getAvailableDTbyTool($tool) {
+function getAvailableDTbyTool($tool)
+{
$dt = $GLOBALS['toolsCol']->find(array("external" => true, "_id" => $tool), array("input_files_combinations_internal" => true))->toArray();
$array = array();
$c = 0;
- foreach($dt as $tool) {
+ foreach ($dt as $tool) {
- foreach($tool["input_files_combinations_internal"] as $combination) {
+ foreach ($tool["input_files_combinations_internal"] as $combination) {
$array[$c]["id"] = $tool["_id"];
- foreach($combination as $single_c) {
+ foreach ($combination as $single_c) {
- foreach($single_c as $k => $v) {
+ foreach ($single_c as $k => $v) {
$array[$c]["list"][] = $k;
-
}
-
}
-
}
-
}
$array[0]["list"] = array_unique($array[0]["list"]);
@@ -131,20 +125,20 @@ function getAvailableDTbyTool($tool) {
$array = $array[0];
return $array;
-
}
// return tools valid for a list of given files
-function getTools_ByDT($toolsDT, $filesDT) {
+function getTools_ByDT($toolsDT, $filesDT)
+{
$toolsList = array();
// foreach de totes les possible combinacions de tools
- foreach($toolsDT as $tdt) {
+ foreach ($toolsDT as $tdt) {
// només entrem si hi ha igual o més fitxers seleccionats que a list1 (obligatoris)
- if(sizeof($tdt["list1"]) <= sizeof($filesDT)) {
+ if (sizeof($tdt["list1"]) <= sizeof($filesDT)) {
$list1 = $tdt["list1"];
$list2 = $tdt["list2"];
@@ -152,19 +146,18 @@ function getTools_ByDT($toolsDT, $filesDT) {
$listF = $filesDT;
// foreach de tots els fitxers seleccionats
- foreach($listF as $itemWS) {
+ foreach ($listF as $itemWS) {
// if item is in list1, unset
- if(in_array($itemWS, $list1)) {
+ if (in_array($itemWS, $list1)) {
$key = array_search($itemWS, $list1);
unset($list1[$key]);
$key = array_search($itemWS, $listF);
unset($listF[$key]);
-
} /*else*/
- if(in_array($itemWS, $list2)) {
+ if (in_array($itemWS, $list2)) {
// només que n'hi hagi un els esborrem tots???
$key = array_search($itemWS, $list2);
@@ -179,12 +172,11 @@ function getTools_ByDT($toolsDT, $filesDT) {
}*/
$listF = array_diff($listF, [$itemWS]);
-
- }
- if(in_array($itemWS, $list3)) {
+ }
+ if (in_array($itemWS, $list3)) {
$toolsList[] = $tdt["id"];
}
-
+
/*else {
break;
@@ -194,69 +186,62 @@ function getTools_ByDT($toolsDT, $filesDT) {
//if(!in_array($itemWS, $list1) && !in_array($itemWS, $list2)) break;
}
-
+
// if no more items on both lists, it means matching!
- if((sizeof($list1) == 0) && (sizeof($list2) == 0) && (sizeof($listF) == 0)) $toolsList[] = $tdt["id"];
+ if ((sizeof($list1) == 0) && (sizeof($list2) == 0) && (sizeof($listF) == 0)) $toolsList[] = $tdt["id"];
}
-
}
$toolsList = array_unique($toolsList);
return $toolsList;
-
}
-function getTools_ListByID($array, $status) {
-
+function getTools_ListByID($array, $status)
+{
$array = array_values($array);
-
$tl = $GLOBALS['toolsCol']->find(array('_id' => array('$in' => $array), 'status' => array('$in' => [$status, 3])), array("name" => true, "status" => true));
+ if ($_SESSION['User']['Type'] == UserType::ToolDev->value) {
- if($_SESSION['User']['Type'] == 1) {
-
- $tools_list = iterator_to_array($tl, false);
-
- foreach($tools_list as $key => $tool) {
+ $tools_list = iterator_to_array($tl, false);
- if($tool["status"] == 3 && !in_array($tool["_id"], $_SESSION['User']["ToolsDev"])) {
- unset($tools_list[$key]);
- }
+ foreach ($tools_list as $key => $tool) {
- }
-
- return $tools_list;
+ if ($tool["status"] == 3 && !in_array($tool["_id"], $_SESSION['User']["ToolsDev"])) {
+ unset($tools_list[$key]);
+ }
+ }
- } else {
+ return $tools_list;
+ } else {
return iterator_to_array($tl, false);
-
- }
-
+ }
}
-function getSingleTool_Help($toolID, $op) {
+function getSingleTool_Help($toolID, $op)
+{
$tool = $GLOBALS['toolsCol']->findOne(array("external" => true, "_id" => $toolID), array("input_files_combinations" => true, "input_files" => true));
$c = 0;
- if (!isset($tool["input_files_combinations"])){
- $_SESSION['errorData']['Error'][]="TOOL ".$tool['_id']." no internal comb";
+ if (!isset($tool["input_files_combinations"])) {
+ $_SESSION['errorData']['Error'][] = "TOOL " . $tool['_id'] . " no internal comb";
next;
}
- foreach($tool["input_files_combinations"] as $combination) {
+ foreach ($tool["input_files_combinations"] as $combination) {
- if($c == $op) {
+ if ($c == $op) {
$array[$c]["id"] = $tool["_id"];
$array[$c]["operation"] = $combination["description"];
$array[$c]["content"] = [];
- foreach($tool["input_files"] as $inputf) {
+ foreach ($tool["input_files"] as $inputf) {
- if(in_array($inputf["name"], $combination["input_files"])) {
+ if (in_array($inputf["name"], $combination["input_files"])) {
$a = [];
$a["description"] = $inputf["description"];
@@ -268,7 +253,7 @@ function getSingleTool_Help($toolID, $op) {
$a["format"] = $inputf["file_type"];
$b = [];
- foreach($inputf["data_type"] as $dt) {
+ foreach ($inputf["data_type"] as $dt) {
$b[] = getDataTypeName($dt);
//$n = iterator_to_array($n, true);
@@ -280,20 +265,17 @@ function getSingleTool_Help($toolID, $op) {
$array[$c]["content"][] = $a;
}
-
}
-
}
- $c ++;
-
+ $c++;
}
return $array;
-
}
-function getTools_Help() {
+function getTools_Help()
+{
$dt = $GLOBALS['toolsCol']->find(array("external" => true), array("input_files_combinations" => true, "input_files" => true));
@@ -301,22 +283,22 @@ function getTools_Help() {
$c = 0;
- foreach($dt as $tool) {
+ foreach ($dt as $tool) {
- if (!isset($tool["input_files_combinations"])){
- $_SESSION['errorData']['Error'][]="TOOL ".$tool['_id']." no internal comb";
+ if (!isset($tool["input_files_combinations"])) {
+ $_SESSION['errorData']['Error'][] = "TOOL " . $tool['_id'] . " no internal comb";
next;
}
- foreach($tool["input_files_combinations"] as $combination) {
+ foreach ($tool["input_files_combinations"] as $combination) {
$array[$c]["id"] = $tool["_id"];
$array[$c]["operation"] = $combination["description"];
$array[$c]["content"] = [];
- foreach($tool["input_files"] as $inputf) {
+ foreach ($tool["input_files"] as $inputf) {
- if(in_array($inputf["name"], $combination["input_files"])) {
+ if (in_array($inputf["name"], $combination["input_files"])) {
$a = [];
$a["description"] = $inputf["description"];
@@ -328,7 +310,7 @@ function getTools_Help() {
$a["format"] = $inputf["file_type"];
$b = [];
- foreach($inputf["data_type"] as $dt) {
+ foreach ($inputf["data_type"] as $dt) {
$b[] = getDataTypeName($dt);
//$n = iterator_to_array($n, true);
@@ -340,73 +322,66 @@ function getTools_Help() {
$array[$c]["content"][] = $a;
}
-
}
- $c ++;
-
+ $c++;
}
-
}
return $array;
-
}
// FILTER VISUALIZERS
-function getFiles_FileTypes($fn) {
+function getFiles_FileTypes($fn)
+{
$fdt = $GLOBALS['filesMetaCol']->find(array('_id' => array('$in' => $fn)), array("_id" => false, "format" => true));
$a = array();
- foreach($fdt as $v) $a[] = $v["format"];
+ foreach ($fdt as $v) $a[] = $v["format"];
return $a;
-
}
-function getVisualizers_FileTypes() {
+function getVisualizers_FileTypes()
+{
$dt = $GLOBALS['visualizersCol']->find(array("external" => true), array("accepted_file_types" => true));
$array = array();
- foreach($dt as $viewer) {
+ foreach ($dt as $viewer) {
$array[] = $viewer;
-
}
return $array;
-
}
-function getVisualizers_ByFT($visFT, $filesFT) {
-
+function getVisualizers_ByFT($visFT, $filesFT)
+{
+
$visualizersList = array();
- foreach($visFT as $vft) {
+ foreach ($visFT as $vft) {
$accepted = false;
- if(count(array_intersect($filesFT, $vft["accepted_file_types"])) == count($filesFT)) {
+ if (count(array_intersect($filesFT, $vft["accepted_file_types"])) == count($filesFT)) {
$visualizersList[] = $vft["_id"];
-
}
-
}
return $visualizersList;
-
}
-function getVisualizers_ListByID($array) {
+function getVisualizers_ListByID($array)
+{
$tl = $GLOBALS['visualizersCol']->find(array('_id' => array('$in' => $array)), array("name" => true));
return iterator_to_array($tl, false);
-
}
diff --git a/front_end/openVRE/public/phplib/users.inc.php b/front_end/openVRE/public/phplib/users.inc.php
index fe354f47..753fd0e3 100644
--- a/front_end/openVRE/public/phplib/users.inc.php
+++ b/front_end/openVRE/public/phplib/users.inc.php
@@ -8,219 +8,168 @@
//require_once "classes/User.php";
-function checkLoggedIn(){
+function checkLoggedIn()
+{
- if (isset($_SESSION['User']) && isset($_SESSION['User']['_id']))
- $user = $GLOBALS['usersCol']->findOne(array('_id' => $_SESSION['User']['_id']));
-
- if(isset($_SESSION['User']) && ($user['Status'] == 1)) return true;
- else return false;
-}
-
-function checkTermsOfUse() {
+ if (isset($_SESSION['User']) && isset($_SESSION['User']['_id'])) {
+ $user = getUserById($_SESSION['User']['_id']);
+ }
- if(isset($_SESSION['User']['terms']) and $_SESSION['User']['terms']== 1) return true;
- else return false;
+ return isset($_SESSION['User']) && ($user['Status'] == UserStatus::Active->value);
}
-function checkAdmin() {
-
- $user = $GLOBALS['usersCol']->findOne(array('_id' => $_SESSION['User']['_id']));
-
- if(isset($_SESSION['User']) && ($user['Status'] == 1) && (allowedRoles($user['Type'], $GLOBALS['ADMIN']))) return true;
- else return false;
+function checkTermsOfUse()
+{
+ return isset($_SESSION['User']['terms']) && $_SESSION['User']['terms'] == 1;
}
-function checkToolDev() {
-
- $user = $GLOBALS['usersCol']->findOne(array('_id' => $_SESSION['User']['_id']));
+function checkAdmin()
+{
+ $user = getUserById($_SESSION['User']['_id']);
- if(isset($_SESSION['User']) && ($user['Status'] == 1) && (allowedRoles($user['Type'], $GLOBALS['TOOLDEV']) || allowedRoles($user['Type'], $GLOBALS['ADMIN']))) return true;
- else return false;
+ return isset($_SESSION['User']) && ($user['Status'] == UserStatus::Active->value) && (allowedRoles($user['Type'], $GLOBALS['ADMIN']));
}
-// create user - from sign up
-function createUser(&$f) {
-
- // create full user object
- $objUser = new User($f, True);
- $aux = (array)$objUser;
-
- //load user in current session
- $_SESSION['userId'] = $aux['id']; //OBSOLETE
- $_SESSION['User'] = $aux;
- unset($_SESSION['crypPassword']);
-
- // create user directory
- $dataDirId = prepUserWorkSpace($aux['id'],$aux['activeProject']);
- if (!$dataDirId){
- $_SESSION['errorData']['Error'][]="Error creating data dir";
- echo "Error creating data dir";
- return false;
- }
- $aux['dataDir'] = $dataDirId;
- $aux['AuthProvider']= "ldap-cloud";
- $_SESSION['User']['dataDir'] = $dataDirId;
-
- // register user into mongo
- $r = saveNewUser($aux);
- if (!$r){
- $_SESSION['errorData']['Error'][]="User creation failed while registering it into the database. Please, manually clean orphan files for ".$aux['id']. "(".$dataDirId.")";
- echo 'Error saving new user into Mongo database';
- unset($_SESSION['User']);
- return false;
- }
-
- /*
- // register user in MuG ldap
- $r = saveNewUser_ldap($aux);
- if (!$r){
- $_SESSION['errorData']['Error'][]="Failed to register ".$userObj['id']." into LDAP";
- $_SESSION['errorData']['Error'][]="User creation failed while registering it to LDAP. Please,
DELETE USER";
- unset($_SESSION['User']);
- return false;
- }
- */
+function checkToolDev()
+{
+ $user = getUserById($_SESSION['User']['_id']);
- // send mail
- sendWelcomeToNewUser($aux['_id'], $aux['Name'], $aux['Surname']);
- return true;
+ return isset($_SESSION['User']) && ($user['Status'] == UserStatus::Active->value) && (allowedRoles($user['Type'], $GLOBALS['TOOLDEV']) || allowedRoles($user['Type'], $GLOBALS['ADMIN']));
}
// create user - after being authentified by the Auth Server
-function createUserFromToken($login,$token,$jwt,$userinfo=array(),$anonID=false){
-
- // create full user oject
- if (!$anonID){
- $f = array(
+function createUserFromToken($login, $token, $jwt, $userinfo = array(), $anonID = false)
+{
+ if (!$anonID) {
+ $userAttributes = array(
"Email" => $login,
- "Token" => $token,
"JWT" => $jwt,
- "Type" => 2
+ "Type" => UserType::Registered->value
);
- }else{
- $f = checkUserLoginExists($anonID);
+ } else {
+ $userAttributes = getUserById($anonID);
// overwrite currently logged anon user
- if ($f){
- $f["Email"] = $login;
- $f["Token"] = $token;
- $f["JWT"] = $jwt;
- $f["Type"] = 2;
-
- }else{
- $f = array(
- "Email" => $login,
- "Token" => $token,
- "JWT" => $jwt,
- "Type" => 2
- );
+ if ($userAttributes) {
+ $userAttributes["Email"] = $login;
+ $userAttributes["JWT"] = $jwt;
+ $userAttributes["Type"] = UserType::Registered->value;
+ } else {
+ $userAttributes = array(
+ "Email" => $login,
+ "JWT" => $jwt,
+ "Type" => UserType::Registered->value
+ );
}
}
- if (isset($userinfo) && $userinfo){
- if (isset($userinfo['family_name']))
- $f['Surname'] = $userinfo['family_name'];
- if (isset($userinfo['given_name']))
- $f['Name'] = $userinfo['given_name'];
- if (isset($userinfo['provider']))
- $f['AuthProvider'] = $userinfo['provider'];
- $f['TokenInfo'] = $userinfo;
+
+ $_SESSION['userToken'] = $token;
+ if (isset($userinfo) && $userinfo) {
+ if (isset($userinfo['family_name'])) {
+ $userAttributes['Surname'] = $userinfo['family_name'];
+ }
+
+ if (isset($userinfo['given_name'])) {
+ $userAttributes['Name'] = $userinfo['given_name'];
+ }
+
+ if (isset($userinfo['provider'])) {
+ $userAttributes['AuthProvider'] = $userinfo['provider'];
+ }
+ $_SESSION['tokenInfo'] = $userinfo;
}
- $objUser = new User($f, True);
- if (!$objUser)
+
+ $objUser = new User($userAttributes['Email'], $userAttributes['Surname'], $userAttributes['Name'], "", $userAttributes['Type'], "", "", $userAttributes['AuthProvider'], "", $userAttributes['JWT']);
+ if (!$objUser) {
return false;
- $aux = (array)$objUser;
+ }
+ $userArray = (array) $objUser;
//load user in current session
- $_SESSION['userId'] = $aux['id']; //OBSOLETE
- $_SESSION['User'] = $aux;
- unset($_SESSION['crypPassword']);
+ $_SESSION['userId'] = $userArray['id']; //OBSOLETE
+ $_SESSION['User'] = $userArray;
// create user directory
- if (!$aux['dataDir']){
+ if (!$userArray['dataDir']) {
// create new workspace
- $dataDirId = prepUserWorkSpace($aux['id'],$aux['activeProject']);
- if (!$dataDirId){
- $_SESSION['errorData']['Error'][]="Error creating data dir";
- echo "Error creating data dir";
+ $dataDirId = prepUserWorkSpace($userArray['id'], $userArray['activeProject']);
+ if (!$dataDirId) {
+ $_SESSION['errorData']['Error'][] = "Error creating data dir";
+
return false;
}
- $aux['dataDir']= $dataDirId;
+
+ $userArray['dataDir'] = $dataDirId;
$_SESSION['User']['dataDir'] = $dataDirId;
- }else{
+ } else {
// change ownership for re-used workspace
- $workspace_files = getGSFileIdsFromDir($aux['dataDir'],1);
- foreach ($workspace_files as $fn){
+ $workspace_files = getGSFileIdsFromDir($userArray['dataDir'], 1);
+ foreach ($workspace_files as $fn) { // TODO: complete or remove
}
}
- // register user in mongo. NOT in ldap, as user exists for a oauth2 provider
- $r = saveNewUser($aux);
- if (!$r){
- $_SESSION['errorData']['Error'][]="User creation failed while registering it into the database. Please, manually clean orphan files for ".$aux['id']. "(".$dataDirId.")";
+ // register user in mongo. NOT in ldap, as user exists for a oauth2 provider
+ $r = saveNewUser($userArray);
+ if (!$r) {
+ $_SESSION['errorData']['Error'][] = "User creation failed while registering it into the database. Please, manually clean orphan files for " . $userArray['id'] . "(" . $dataDirId . ")";
echo 'Error saving new user into Mongo database';
- unset($_SESSION['User']);
+ unset($_SESSION['User']);
+
return false;
}
- if ($anonID){
- // if replacing anon user, delete old anon from mongo
-// $GLOBALS['usersCol']->deleteOne(array('_id'=> $anonID));
+ if ($anonID) { // TODO: complete or remove
+ // if replacing anon user, delete old anon from mongo
+ // $GLOBALS['usersCol']->deleteOne(array('_id'=> $anonID));
}
-
- // DEPRECATED
- // inject user['id'] into auth server (keycloak) as 'vre_id' (so APIs will find it in /openid-connect/userinfo endpoint)
- #$r = injectMugIdToKeycloak($aux['_id'],$aux['id']);
// if not all user metadata mapped from oauth2 provider, ask the user
- if (!$aux['Name'] || !$aux['Surname'] || !$aux['Inst'] || !$aux['Country']){
- redirect($GLOBALS['BASEURL'].'user/usrProfile.php');
+ if (!$userArray['Name'] || !$userArray['Surname'] || !$userArray['Inst']) {
+ redirect($GLOBALS['BASEURL'] . 'user/usrProfile.php');
exit(0);
}
+
return true;
}
// create anonymous user - without being authentified by the Auth Server
-function createUserAnonymous($sampleData=""){
-
- // create full user oject
-
- $f = array(
- "Email" => substr(md5(rand()),0,25)."",
- "Type" => 3,
+function createUserAnonymous($sampleData)
+{
+ $userAttributes = array(
+ "Email" => substr(md5(rand()), 0, 25) . "",
+ "Type" => UserType::Guest->value,
"Name" => "Guest",
"Surname" => "",
"AuthProvider" => "VRE"
);
- $objUser = new User($f, False);
- if (!$objUser)
- return false;
- $aux = (array)$objUser;
- //load user in current session
- $_SESSION['userId'] = $aux['id']; //OBSOLETE
- $_SESSION['User'] = $aux;
- $_SESSION['anonID'] = $aux['Email'];
+ $objUser = new User($userAttributes['Email'], $userAttributes['Surname'], $userAttributes['Name'], "", $userAttributes['Type'], "", "", $userAttributes['AuthProvider'], "", "");
+ if (!$objUser) {
+ return false;
+ }
+ $userArray = (array) $objUser;
+ $_SESSION['userId'] = $userArray['id']; //TODO: OBSOLETE?
+ $_SESSION['User'] = $userArray;
+ $_SESSION['anonID'] = $userArray['Email'];
- // create user directory
- $dataDirId = prepUserWorkSpace($aux['id'],$aux['activeProject'],$sampleData);
- if (!$dataDirId){
- $_SESSION['errorData']['Error'][]="Error creating data dir";
- echo "Error creating data dir";
+ $dataDirId = prepUserWorkSpace($userArray['id'], $userArray['activeProject'], $sampleData);
+ if (!$dataDirId) {
+ $_SESSION['errorData']['Error'][] = "Error creating data dir";
return false;
}
- $aux['dataDir']= $dataDirId;
- $aux['terms'] = "1";
+
+ $userArray['dataDir'] = $dataDirId;
+ $userArray['terms'] = "1";
$_SESSION['User']['dataDir'] = $dataDirId;
$_SESSION['User']['terms'] = "1";
-
// register user in mongo. NOT in ldap nor in the oauth2 provider
- $r = saveNewUser($aux);
- if (!$r){
- $_SESSION['errorData']['Error'][]="User creation failed while registering it into the database. Please, manually clean orphan files for ".$aux['id']. "(".$dataDirId.")";
+ $r = saveNewUser($userArray);
+ if (!$r) {
+ $_SESSION['errorData']['Error'][] = "User creation failed while registering it into the database. Please, manually clean orphan files for " . $userArray['id'] . "(" . $dataDirId . ")";
echo 'Error saving new user into Mongo database';
- unset($_SESSION['User']);
+ unset($_SESSION['User']);
+
return false;
}
@@ -228,367 +177,331 @@ function createUserAnonymous($sampleData=""){
}
-// create user - from Admin section
-function createUserFromAdmin(&$f) {
+function getUserById($id, $options = array())
+{
+ return $GLOBALS['usersCol']->findOne(["_id" => $id], $options);
+}
+
- // create full user object
- $objUser = new User($f, True);
- $aux = (array)$objUser;
- $_SESSION['errorData']['Info'][] = "New user data object created. Login = ".$aux['_id']." Password = ".$f['pass1'];
+function getUserByType($type, $options = array())
+{
+ return $GLOBALS['usersCol']->findOne(["Type" => $type], $options);
+}
- // create user directory
- $dataDirId = prepUserWorkSpace($aux['id'],$aux['activeProject'],$f['DataSample'],array(),TRUE,1);
- if (!$dataDirId){
- $_SESSION['errorData']['Error'][] = "Error creating new user directory with '".$aux['id']."'. If needed
delete user";
- echo "Error creating data dir";
- return false;
- }
- $_SESSION['errorData']['Info'][] = "New workspace created at '".$aux['id']."' (id=$dataDirId).";
- $aux['dataDir']= $dataDirId;
- $aux['AuthProvider']= "ldap-cloud";
-
- // register user in mongo
- $r = saveNewUser($aux);
- if (!$r){
- $_SESSION['errorData']['Error'][]="User creation failed while registering it into the database. Please, manually clean orphan files for ".$aux['id']. "(".$dataDirId.")";
- echo 'Error saving new user into Mongo database';
- }
- $_SESSION['errorData']['Info'][] = "New user successfuly created";
-
- /*
- // register user in MuG ldap
- $r = saveNewUser_ldap($aux);
- if (!$r){
- $_SESSION['errorData']['Error'][]="Failed to register ".$userObj['id']." into LDAP";
- $_SESSION['errorData']['Error'][]="User creation failed while registering it to LDAP. Please,
DELETE USER";
- return false;
- }*/
- // send mail to user, if selected
- if($f['sendEmail'] == 1) sendPasswordToNewUser($f['Email'], $f['Name'], $f['Surname'], $f['pass1']);
-
- return true;
+function getUsersByFilter($filter, $options = array())
+{
+ return $GLOBALS['usersCol']->find($filter, $options);
}
// load user to SESSION
-function setUser($f,$lastLogin=FALSE) {
+function setUser($f, $lastLogin = FALSE)
+{
$aux = (array)$f;
- unset($aux['crypPassword']);
- //unset($aux['lastLogin']);
$_SESSION['User'] = $aux;
- $_SESSION['curDir'] = $_SESSION['User']['id'];
+ $_SESSION['curDir'] = $_SESSION['User']['id'];
- if(!isset($_SESSION['lastUserLogin']) && $lastLogin) $_SESSION['lastUserLogin'] = $lastLogin;
+ if (!isset($_SESSION['lastUserLogin']) && $lastLogin) $_SESSION['lastUserLogin'] = $lastLogin;
}
-function delUser($id, $asRoot=1, $force=false){
+function delUser($id, $asRoot = 1, $force = false)
+{
//delete data from Mongo and disk
-
+
$homePath = $id;
- $homeId = getGSFileId_fromPath($homePath,$asRoot);
- if (!$homeId){
+ $homeId = getGSFileId_fromPath($homePath, $asRoot);
+ if (!$homeId) {
$homePath = "$id/";
- $homeId = getGSFileId_fromPath($homePath,$asRoot);
+ $homeId = getGSFileId_fromPath($homePath, $asRoot);
}
- if ($homeId){
- $home = getGSFile_fromId($homeId,"all",$asRoot);
-
- $r = deleteGSDirBNS($homeId,$asRoot,$force);
- if ($r == 0){
- $_SESSION['errorData']['Error'][]="Cannot delete $homeId directory from database.";
- if (!$force){return 0;}
+ if ($homeId) {
+ $home = getGSFile_fromId($homeId, "all", $asRoot);
+
+ $r = deleteGSDirBNS($homeId, $asRoot, $force);
+ if ($r == 0) {
+ $_SESSION['errorData']['Error'][] = "Cannot delete $homeId directory from database.";
+ if (!$force) {
+ return 0;
+ }
+ }
+ } else {
+ if (!$force) {
+ $_SESSION['errorData']['Error'][] = "Cannot delete user. It has no data registered, at least homeDir '$id/' is not found in DB";
+ return 0;
}
- }else{
- if (!$force){
- $_SESSION['errorData']['Error'][]="Cannot delete user. It has no data registered, at least homeDir '$id/' is not found in DB";
- return 0;
- }
}
- $rfn = $GLOBALS['dataDir']."/".$homePath;
- if (is_dir($rfn)){
- exec ("rm -r \"$rfn\" 2>&1",$output);
+ $rfn = $GLOBALS['dataDir'] . "/" . $homePath;
+ if (is_dir($rfn)) {
+ exec("rm -r \"$rfn\" 2>&1", $output);
}
- /*
- //delete user from KC
- $user = $GLOBALS['usersCol']->findOne(array('id' => $id));
- $r = delUser_ldap($user['_id']);
- */
-
//delete user from mongo
- $GLOBALS['usersCol']->deleteOne(array('id'=> $id));
+ $GLOBALS['usersCol']->deleteOne(array('id' => $id));
return 1;
}
-function injectMugIdToKeycloak($login,$id){
+function injectMugIdToKeycloak($login, $id)
+{
$kc_token = get_keycloak_admintoken();
- if ($kc_token && isset($kc_token['access_token'])){
- $kc_user = get_keycloak_user($login,$kc_token['access_token']);
-print "\n\n\nKC USER\n";
-var_dump($kc_user);
- if ($kc_user && isset($kc_user['id'])){
+ if ($kc_token && isset($kc_token['access_token'])) {
+ $kc_user = get_keycloak_user($login, $kc_token['access_token']);
+ print "\n\n\nKC USER\n";
+ var_dump($kc_user);
+ if ($kc_user && isset($kc_user['id'])) {
$attributes = array();
if ($kc_user['attributes'])
$attributes = $kc_user['attributes'];
$attributes['vre_id'] = array($id);
- $data = array("attributes" => $attributes);
-print "\nPOST DATA\n";
-var_dump(json_encode($data));
- $r = update_keycloak_user($kc_user['id'],json_encode($data),$kc_token['access_token']);
+ $data = array("attributes" => $attributes);
+ print "\nPOST DATA\n";
+ var_dump(json_encode($data));
+ $r = update_keycloak_user($kc_user['id'], json_encode($data), $kc_token['access_token']);
- if (!$r){
- $_SESSION['errorData']['Warning'][]="User not valid to be used outside VRE. Could not inject 'vre_id' into Auth Server. Cannot update ".$aux['_id']." in its registry";
+ if (!$r) {
+ $_SESSION['errorData']['Warning'][] = "User not valid to be used outside VRE. Could not inject 'vre_id' into Auth Server. Cannot update " . $aux['_id'] . " in its registry";
return false;
- }else{
+ } else {
return true;
}
- }else{
- $_SESSION['errorData']['Warning'][]="User not valid to be used outside VRE. Could not inject 'vre_id' into Auth Server. Cannot get ".$aux['_id']." from its registry";
+ } else {
+ $_SESSION['errorData']['Warning'][] = "User not valid to be used outside VRE. Could not inject 'vre_id' into Auth Server. Cannot get " . $aux['_id'] . " from its registry";
return false;
}
- }else{
- $_SESSION['errorData']['Warning'][]="User not valid to be used outside VRE. Could not inject 'vre_id' into Auth Server. Token not created";
+ } else {
+ $_SESSION['errorData']['Warning'][] = "User not valid to be used outside VRE. Could not inject 'vre_id' into Auth Server. Token not created";
return false;
}
}
-function resetPasswordViaKeycloak($login,$id){
+function resetPasswordViaKeycloak($login, $id)
+{
$kc_token = get_keycloak_admintoken();
- if ($kc_token && isset($kc_token['access_token'])){
- $kc_user = get_keycloak_user($login,$kc_token['access_token']);
- if ($kc_user && isset($kc_user['id'])){
+ if ($kc_token && isset($kc_token['access_token'])) {
+ $kc_user = get_keycloak_user($login, $kc_token['access_token']);
+ if ($kc_user && isset($kc_user['id'])) {
- $r = update_keycloak_userPass($kc_user['id'],$kc_token['access_token']);
+ $r = update_keycloak_userPass($kc_user['id'], $kc_token['access_token']);
- if (!$r){
- $_SESSION['errorData']['Warning'][]="Cannot reset password from VRE. Cannot update ".$aux['_id']." registration entry";
+ if (!$r) {
+ $_SESSION['errorData']['Warning'][] = "Cannot reset password from VRE. Cannot update " . $aux['_id'] . " registration entry";
return false;
- }else{
+ } else {
return true;
}
- }else{
- $_SESSION['errorData']['Warning'][]="Cannot reset password from VRE.";
+ } else {
+ $_SESSION['errorData']['Warning'][] = "Cannot reset password from VRE.";
return false;
}
- }else{
- $_SESSION['errorData']['Warning'][]="Cannot reset password from VRE. Token not created";
+ } else {
+ $_SESSION['errorData']['Warning'][] = "Cannot reset password from VRE. Token not created";
return false;
}
}
-
-
-function logoutUser() {
+
+
+function logoutUser()
+{
session_unset();
}
-function logoutAnon() {
+function logoutAnon()
+{
unset($_SESSION['User']);
+ unset($_SESSION['userToken']);
+ unset($_SESSION['userInfo']);
}
-function saveNewUser($userObj) {
- $r = $GLOBALS['usersCol']->insertOne($userObj);
- if (!$r)
+function saveNewUser($user)
+{
+ $r = $GLOBALS['usersCol']->insertOne($user);
+ if (!$r) {
return false;
+ }
return true;
}
-// update user document in Mongo
-
-function updateUser($f) {
- $GLOBALS['usersCol']->updateOne(array('_id' => $f['_id']), array('$set'=>$f), array('upsert=>true'));
-}
-
-
-// update user document in Mongo true or false
-function updateUserNew($f) {
- try {
- $result = $GLOBALS['usersCol']->updateOne(['_id' => $f['_id']], ['$set' => $f], ['upsert' => true]);
- return $result->getModifiedCount() > 0 || $result->getUpsertedCount() > 0;
- } catch (Exception $e) {
- // Handle the exception if needed
- return false;
- }
+function updateUser($user)
+{
+ $GLOBALS['usersCol']->updateOne(array('_id' => $user['_id']), array('$set' => $user), array('upsert=>true'));
}
// update attribute user document in Mongo
-function modifyUser($login,$attribute,$value) {
- $GLOBALS['usersCol']->updateOne(array('_id' => $login ),
- array('$set' => array($attribute => $value)),
- array('upsert' => true)
- );
-}
-
-function checkUserIDExists($userId) {
- $user= array();
- if ($userId)
- $user = $GLOBALS['usersCol']->findOne(array('id' => $userId));
-
- return $user;
+function modifyUser($login, $attribute, $value)
+{
+ $GLOBALS['usersCol']->updateOne(
+ array('_id' => $login),
+ array('$set' => array($attribute => $value)),
+ array('upsert' => true)
+ );
}
-function checkUserLoginExists($login) {
- $user= array();
- if ($login)
- $user = $GLOBALS['usersCol']->findOne(array('_id' => $login));
-
- return $user;
-}
-function loadUser($login, $pass) {
-
+function loadUser($login, $pass)
+{
// check user exists
- $user = $GLOBALS['usersCol']->findOne(array('_id' => $login));
- if (!$user['_id'] || $user['Status'] == 0) {
- $_SESSION['errorData']['Error'][]="Requested user (_id = $login) not found. Cannot load user.";
+ $user = getUserById($login);
+ if (!$user['_id'] || $user['Status'] == UserStatus::Inactive->value) {
+ $_SESSION['errorData']['Error'][] = "Requested user (_id = $login) not found. Cannot load user.";
return False;
}
// check pass/token verifies - except when loading an ANON or when impersonating
- $pass_verified = check_password($pass, $user['crypPassword']);
- $impersonating = (isset($_SESSION['User']) && $_SESSION['User']['Type'] == 0 && $pass == 99 ? TRUE : FALSE );
- $loadingAnon = ($user['Type'] == 3 ? TRUE : FALSE );
+ $pass_verified = check_password($pass, null);
+ $impersonating = (isset($_SESSION['User']) && $_SESSION['User']['Type'] == UserType::Admin->value && $pass == 99 ? TRUE : FALSE);
+ $loadingAnon = ($user['Type'] == UserType::Guest ? TRUE : FALSE);
- if (!$pass_verified){
- if (!$loadingAnon && !$impersonating){
+ if (!$pass_verified) {
+ if (!$loadingAnon && !$impersonating) {
//$_SESSION['errorData']['Error'][]="Trying to load user without password from SESSION data. Rejected!";
// keep open SESSION
$user['lastReload'] = moment();
updateUser($user);
setUser($user);
return False;
- }else{
- if ($impersonating){
- $_SESSION['errorData']['Info'][]="User $login successfully impersonated!";
+ } else {
+ if ($impersonating) {
+ $_SESSION['errorData']['Info'][] = "User $login successfully impersonated!";
}
}
}
// edit user to load
- $auxlastlog = $user['lastLogin'];
+ $auxlastlog = $user['lastLogin'];
$user['lastLogin'] = moment();
updateUser($user);
-
+
// load user into SESSION
- setUser($user,$auxlastlog);
+ setUser($user, $auxlastlog);
return $user;
}
-function loadUserWithToken($userinfo, $token,$jwt){
- $login = $userinfo['email'];
- $user = $GLOBALS['usersCol']->findOne(array('_id' => $login));
+function loadUserWithToken($userinfo, $token, $jwt)
+{
+ $user = getUserById($userinfo['email']);
+ if (!$user['_id'] || $user['Status'] == UserStatus::Inactive->value) {
+ return false;
+ }
- if (!$user['_id'] || $user['Status'] == 0)
- return False;
-
$auxlastlog = $user['lastLogin'];
$user['lastLogin'] = moment();
- $user['Token'] = $token;
$user['JWT'] = $jwt;
- $user['TokenInfo'] = $userinfo;
-
+ $_SESSION['userToken'] = $token;
+ $_SESSION['tokenInfo'] = $userinfo;
+
updateUser($user);
- setUser($user,$auxlastlog);
+ setUser($user, $auxlastlog);
return $user;
}
-function allowedRoles($role, $allowed){
-
- if(in_array($role,$allowed)){
- return true;
- }else{
- return false;
- }
+function allowedRoles($role, $allowed)
+{
+ if (in_array($role, $allowed)) {
+ return true;
+ } else {
+ return false;
+ }
}
-function getUser_diskQuota($login) {
- $r = $GLOBALS['usersCol']->findOne(array('_id' => $login,
- 'diskQuota'=> array('$exists' => true)
- ));
- if (isset($r['diskQuota']))
- return $r['diskQuota'];
- else
- return false;
+function getUser_diskQuota($login)
+{
+ $r = $GLOBALS['usersCol']->findOne(array(
+ '_id' => $login,
+ 'diskQuota' => array('$exists' => true)
+ ));
+
+ return $r['diskQuota'] ?? false;
}
-function saveUserJobs($login,$jobInfo) {
- $GLOBALS['usersCol']->updateOne(array('_id' => $login),
- array('$set' => array('lastjobs' => $jobInfo)),
- array('upsert' => true));
+function saveUserJobs($login, $jobInfo)
+{
+ $GLOBALS['usersCol']->updateOne(
+ array('_id' => $login),
+ array('$set' => array('lastjobs' => $jobInfo)),
+ array('upsert' => true)
+ );
}
-function delUserJob($login,$pid) {
- $GLOBALS['usersCol']->updateOne(array('_id' => $login),
- array('$unset' => array("lastjobs.$pid" => 1 ))
- );
- //array('$pull' => array("lastjobs" => $pid ))
- //multi
+function delUserJob($login, $pid)
+{
+ $GLOBALS['usersCol']->updateOne(
+ array('_id' => $login),
+ array('$unset' => array("lastjobs.$pid" => 1))
+ );
+ //array('$pull' => array("lastjobs" => $pid ))
+ //multi
}
-function addUserJob($login, $data, $pid) {
+function addUserJob($login, $data, $pid)
+{
$pid = strval($pid);
$lastjobs = getUserJobs($login);
$lastjobs[$pid] = $data;
- $GLOBALS['usersCol']->updateOne(array('_id' => $login),
- array('$set' => array('lastjobs' => $lastjobs)),
- array('upsert' => true)
- );
+ $GLOBALS['usersCol']->updateOne(
+ array('_id' => $login),
+ array('$set' => array('lastjobs' => $lastjobs)),
+ array('upsert' => true)
+ );
}
-function getUserJobs($login) {
- $userLastJobs = $GLOBALS['usersCol']->findOne(array('_id' => $login,
- 'lastjobs'=> array('$exists' => true)
- ));
-
- return $userLastJobs['lastjobs'] ?? [];
+function getUserJobs($login)
+{
+ $userLastJobs = $GLOBALS['usersCol']->findOne(array(
+ '_id' => $login,
+ 'lastjobs' => array('$exists' => true)
+ ));
+
+ return $userLastJobs['lastjobs'] ?? [];
}
-function getAllUserJobs() {
- $r = $GLOBALS['usersCol']->find(array('$nor' => array(
- array('lastjobs'=> array('$exists' => false)),
- array('lastjobs'=> array('$size' => 0)),
- )
- ),
- array("_id" => 1, "lastjobs" => 1, "id" => 1)
- );
+function getAllUserJobs()
+{
+ $r = $GLOBALS['usersCol']->find(
+ array(
+ '$nor' => array(
+ array('lastjobs' => array('$exists' => false)),
+ array('lastjobs' => array('$size' => 0)),
+ )
+ ),
+ array("_id" => 1, "lastjobs" => 1, "id" => 1)
+ );
if (empty($r))
- return Array();
+ return array();
$r_arr = iterator_to_array($r);
// return [login] => array(jobId_1 => job1, jobId_2 => job2)
$result = array();
- foreach ($r_arr as $login => $info){
+ foreach ($r_arr as $login => $info) {
$result[$login] = $info["lastjobs"];
- foreach ($info["lastjobs"] as $job_id => $job){
- $result[$login][$job_id]["userId"]= $info["id"];
+ foreach ($info["lastjobs"] as $job_id => $job) {
+ $result[$login][$job_id]["userId"] = $info["id"];
}
}
return $result;
-
}
-function getUserJobPid($login,$pid) {
- $r = $GLOBALS['usersCol']->findOne(array("_id" => $login,
- "lastjobs.$pid"=> array('$exists' => true)
- ));
- if (isset($r['lastjobs']))
- return $r['lastjobs'];
- else
- return Array();
+function getUserJobPid($login, $pid)
+{
+ $r = $GLOBALS['usersCol']->findOne(array(
+ "_id" => $login,
+ "lastjobs.$pid" => array('$exists' => true)
+ ));
+
+ return $r['lastjobs'] ?? array();
}
diff --git a/front_end/openVRE/public/phplib/users_ldap.inc.php b/front_end/openVRE/public/phplib/users_ldap.inc.php
index d4bb3863..a83a45d8 100644
--- a/front_end/openVRE/public/phplib/users_ldap.inc.php
+++ b/front_end/openVRE/public/phplib/users_ldap.inc.php
@@ -5,42 +5,39 @@
*
*/
-function check_password($password, $hash){
- if ($hash == ''){
+function check_password($password, $hash)
+{
+ if ($hash == '') {
return FALSE;
}
-
- if (substr($hash,0,7) == '{crypt}'){
- if (crypt($password, substr($hash,7)) == substr($hash,7))
- return TRUE;
- return FALSE;
- }elseif (substr($hash,0,4) == '$2y$'){
- if (password_verify($password,$hash))
+ if (substr($hash, 0, 7) == '{crypt}') {
+ if (crypt($password, substr($hash, 7)) == substr($hash, 7))
return TRUE;
- return FALSE;
-
- }elseif (substr($hash,0,5) == '{MD5}'){
- $encrypted_password = '{MD5}' . base64_encode(md5( $password,TRUE));
-
- }elseif (substr($hash,0,6) == '{SHA1}'){
- $encrypted_password = '{SHA}' . base64_encode(sha1( $password, TRUE ));
-
- }elseif (substr($hash,0,6) == '{SSHA}'){
- $salt = substr(base64_decode(substr($hash,6)),20);
- $encrypted_password = '{SSHA}' . base64_encode(sha1( $password.$salt, TRUE ). $salt);
-
- }else {
- $_SESSION['ErrorData']['Error'][] = "Unsupported password hash format ".substr($hash,0,9)."...";
+ return FALSE;
+ } elseif (substr($hash, 0, 4) == '$2y$') {
+ if (password_verify($password, $hash))
+ return TRUE;
+ return FALSE;
+ } elseif (substr($hash, 0, 5) == '{MD5}') {
+ $encrypted_password = '{MD5}' . base64_encode(md5($password, TRUE));
+ } elseif (substr($hash, 0, 6) == '{SHA1}') {
+ $encrypted_password = '{SHA}' . base64_encode(sha1($password, TRUE));
+ } elseif (substr($hash, 0, 6) == '{SSHA}') {
+ $salt = substr(base64_decode(substr($hash, 6)), 20);
+ $encrypted_password = '{SSHA}' . base64_encode(sha1($password . $salt, TRUE) . $salt);
+ } else {
+ $_SESSION['ErrorData']['Error'][] = "Unsupported password hash format " . substr($hash, 0, 9) . "...";
return FALSE;
}
-
+
if ($hash == $encrypted_password)
return TRUE;
- return FALSE;
+ return FALSE;
}
-function fromMongoToLdap($UserMongo){
+function fromMongoToLdap($UserMongo)
+{
$info['objectclass'][0] = "inetOrgPerson";
$info['objectclass'][1] = "posixAccount";
@@ -49,25 +46,18 @@ function fromMongoToLdap($UserMongo){
$info['cn'] = $UserMongo['_id'];
$info['uid'] = $UserMongo['_id'];
$info['mail'] = $UserMongo['Email'];
- $info['userPassword'] = $UserMongo['crypPassword'];
if ($UserMongo['Name'])
$info['givenName'] = $UserMongo['Name'];
if ($UserMongo['Surname'])
- $info['sn']= $UserMongo['Name'];
- if ($UserMongo['Country']){
- $countries = array();
- foreach (array_values(iterator_to_array($GLOBALS['countriesCol']->find(array(),array('country'=>1)))) as $v)
- $countries[$v['_id']] = $v['country'];
- $info['l'] = $countries[$UserMongo['Country']];
- }
+ $info['sn'] = $UserMongo['Name'];
- $info['uidNumber'] = getLastUidNumber()+1;
+ $info['uidNumber'] = getLastUidNumber() + 1;
$info['gidNumber'] = '8901'; // mug posixGroup
- $info['loginShell' ] = '/bin/bash';
- $info['homeDirectory']= "/home/".$UserMongo['id'];
+ $info['loginShell'] = '/bin/bash';
+ $info['homeDirectory'] = "/home/" . $UserMongo['id'];
$info['description'] = 'MuG user created from VRE';
-/*
+ /*
$info['shadowExpire']='-1';
$info['shadowFlag']='0';
$info['shadowWarning']='7';
@@ -77,61 +67,65 @@ function fromMongoToLdap($UserMongo){
return $info;
}
-function saveNewUser_ldap($mongoObj){
+function saveNewUser_ldap($mongoObj)
+{
//create ldap record
$ldif = fromMongoToLdap($mongoObj);
//add entry
- $r = ldap_add($GLOBALS['ldap'],"uid=".$ldif['uid'].",ou=People,dc=cloud,dc=local", $ldif);
- if (!$r){
- $_SESSION['errorData']['Error'][] = "Cannot create new user. LDAP says: [".ldap_errno($GLOBALS['ldap'])."] ".ldap_error($GLOBALS['ldap']);
+ $r = ldap_add($GLOBALS['ldap'], "uid=" . $ldif['uid'] . ",ou=People,dc=cloud,dc=local", $ldif);
+ if (!$r) {
+ $_SESSION['errorData']['Error'][] = "Cannot create new user. LDAP says: [" . ldap_errno($GLOBALS['ldap']) . "] " . ldap_error($GLOBALS['ldap']);
return false;
}
//check new entry
- $sr = ldap_search($GLOBALS['ldap'],$GLOBALS['ldap_dn'],"cn=".$ldif['cn']);
- $info = ldap_get_entries($GLOBALS['ldap'],$sr);
-
+ $sr = ldap_search($GLOBALS['ldap'], $GLOBALS['ldap_dn'], "cn=" . $ldif['cn']);
+ $info = ldap_get_entries($GLOBALS['ldap'], $sr);
+
if ($info[0]["dn"])
return true;
- return false;
+ return false;
}
// search entry
-function checkUserLoginExists_ldap($login) {
+function getUserById_ldap($login)
+{
+
+ $sr = ldap_search($GLOBALS['ldap'], $GLOBALS['ldap_dn'], "uid=" . $login);
+ $info = ldap_get_entries($GLOBALS['ldap'], $sr);
- $sr = ldap_search($GLOBALS['ldap'],$GLOBALS['ldap_dn'],"uid=".$login);
- $info = ldap_get_entries($GLOBALS['ldap'],$sr);
-
if ($info[0]["dn"])
return true;
- return false;
+ return false;
}
// delete entry
-function delUser_ldap($login) {
- if (checkUserLoginExists_ldap($login)){
- $r = ldap_delete($GLOBALS['ldap'],"uid=".$login.",".$GLOBALS['ldap_dn']);
- if (!$r){
- $_SESSION['errorData']['Error'][] = "Cannot delete user. LDAP says: [".ldap_errno($GLOBALS['ldap'])."] ".ldap_error($GLOBALS['ldap']);
- return false;
+function delUser_ldap($login)
+{
+ if (getUserById_ldap($login)) {
+ $r = ldap_delete($GLOBALS['ldap'], "uid=" . $login . "," . $GLOBALS['ldap_dn']);
+ if (!$r) {
+ $_SESSION['errorData']['Error'][] = "Cannot delete user. LDAP says: [" . ldap_errno($GLOBALS['ldap']) . "] " . ldap_error($GLOBALS['ldap']);
+ return false;
+ }
}
- }
- return true;
+ return true;
}
-function getLastUidNumber(){
+function getLastUidNumber()
+{
$s = ldap_search($GLOBALS['ldap'], $GLOBALS['ldap_dn'], 'uidNumber=*');
- if ($s){
+ if ($s) {
ldap_sort($GLOBALS['ldap'], $s, "uidNumber");
$result = ldap_get_entries($GLOBALS['ldap'], $s);
$count = $result['count'];
- $big_uid = $result[$count-1]['uidnumber'][0];
+ $big_uid = $result[$count - 1]['uidnumber'][0];
return $big_uid;
- }else{
+ } else {
return 9998;
}
}
diff --git a/front_end/openVRE/public/user/linkedAccount.php b/front_end/openVRE/public/user/linkedAccount.php
index dcdf1b61..5478f9f5 100644
--- a/front_end/openVRE/public/user/linkedAccount.php
+++ b/front_end/openVRE/public/user/linkedAccount.php
@@ -69,23 +69,10 @@ class="page-header-fixed page-sidebar-closed-hide-logo page-content-white page-c
-
-
+ ?>
@@ -116,8 +103,7 @@ class="page-header-fixed page-sidebar-closed-hide-logo page-content-white page-c
@@ -125,8 +111,15 @@ class="page-header-fixed page-sidebar-closed-hide-logo page-content-white page-c
+
+
@@ -134,13 +127,10 @@ class="page-header-fixed page-sidebar-closed-hide-logo page-content-white page-c
-
@@ -148,293 +138,292 @@ class="fa fa-plus"> Update account
-