Retaining the value of a variable in Perl - javascript

I've a GUI front-end (HTML and JavaScript) a Perl back-end. On clicking a certain button on the home page of the front-end, the Perl back-end receives a specific argument. So this argument leads to change of value of a variable ($checkInfo) which is then given back to the GUI. The GUI now pops up a message which displays $checkInfo and on closing the pop-up, another page (say page 2) opens. On page 2 is a certain button which emails $checkInfo to a certain email address.
The problem I'm facing is that $checkInfo is equal to "" on page 2. On page 1, the back-end returns $checkInfo = something to the GUI but that value is lost when I go to page 2. I've tried declaring $value as state $checkInfo but that doesn't work either. I use $checkInfo only in the main() function.
In the code, all you need to know is that preSubmitCheck::autoSubmitCheck return the value such that $checkInfo->{rc} != 0 and in the first iteration $mode ne 'ticket' but $mode eq 'ticket' in the second iteration. In the second iteration, I need the value of $checkInfo to be the same as the first iteration value.
Perl code:
my $username = defined param("username") ? param("username") : undef;
my $action = defined param("run_type") ? param("run_type") : undef;
my $cit_suite = defined param("cit_suite") ? param("cit_suite") : undef;
my $buildroot = defined param("buildroot") ? param("buildroot") : undef;
my $site = defined param("site") ? lc(param("site")) : undef;
my $branch = defined param("branch") ? param("branch") : undef;
my $hw = defined param("hw") ? param("hw") : undef;
my $variant = defined param("variant") ? param("variant") : undef;
my $num_runs = defined param("num_runs") ? param("num_runs") : undef;
my $justification = defined param("justification") ? param("justification") : undef;
my $mode = defined param("userAction") ? param("userAction") : undef;
my $jobID = defined param("jobID") ? param("jobID") : undef;
my $cancel_type = defined param("canceltype") ? param("canceltype") : undef;
state $checkInfo;
my $error;
my %rtn = (
rc => 0,
message => "All is well."
);
if($mode ne "ticket") {
$checkInfo = preSubmitCheck::autoSubmitCheck($site,$username,$num_runs);
}
if(defined $checkInfo && $checkInfo->{rc} == 0){
my $target = 1;
}
else {
if($mode eq "ticket"){
$error = $checkInfo->{message};
my $rtnFromTicket = sendTicket(
username => $username,
cit_suite => $cit_suite,
action => $action,
buildroot => $buildroot,
site => $site,
branch => $branch,
hw => $hw,
variant => $variant,
num_runs => $original_num_runs,
justification => $justification,
errorMessage => $error
);
$rtn{rc} = 2;
$allMessage .= " Your job couldn't be automatically submitted: ". $error;
$allMessage .= " Email info: ". $rtnFromTicket -> {message};
$rtn{message} = $allMessage;
print "00delimiter00"; # use as a delimiter to split from useless print information, and make the front end got the json data.
print to_json(\%rtn);
exit $rtn{rc};
}
else{
$error = $checkInfo->{message};
$rtn{rc} = $checkInfo->{rc};
if($rtn{rc} == 6) {
$allMessage .= " Your job couldn't be automatically submitted: ". $error. " You can schedule your run or open a ticket with the SMOKES team.";
}
else {
$allMessage .= " Your job couldn't be automatically submitted: ". $error;
}
$rtn{message} = $allMessage;
print "00delimiter00"; # use as a delimiter to split from useless print information, and make the front end got the json data.
print to_json(\%rtn);
exit $rtn{rc};
}
}
GUI code:
var query = "username=<% $ARGS{username} %>";
if(Mode=="all"){
query += "&run_type=Presub_smoke";
}
else {
query += "&run_type=CIT" + "&cit_suite=" + document.getElementById("citsuite").value;
}
query += "&buildroot=" + encodeURIComponent(document.getElementById("buildroot").value);
query += "&site=" + encodeURIComponent(document.getElementById("remoteSite").value);
query += "&branch=" + encodeURIComponent(document.getElementById("branch").value);
query += "&hw=" + encodeURIComponent(document.getElementById("hwtype").value);
query += "&variant=" + encodeURIComponent(document.getElementById("variant").value);
query += "&num_runs=" + document.getElementById("num_runs").value;
query += "&justification=" + encodeURIComponent(document.getElementById("justification").value);
query += "&userAction=" + encodeURIComponent(action);
var submitFcts = new Array();
submitFcts[3] = "updateSubmitInfo";
submitFcts[4] = "return_request";
makeUserRequest2("<% $CGI_form_path %>", query, submitFcts, "");
I hope this suffices for answering my question. Thanks!

state only preserves the value of a variable within a single process. When running as CGI, there's a new process for each HTTP request.
If you want to store state across requests, you will need to persist it somewhere that survives across requests -- for instance, by storing it in a cookie, in a session, or in a database.

Related

Get signature values from PDF (PHP+JS)

How I can get values (date, signing name etc.) from sign('s) inside PDF? At my application on Joomla and Fabrik component i can run PHP and JS code.
The code I am currently using from Stack is not working as expected. If I read on browser $content variable, i cannot see /ByteRange, but when i take it to txt file, there is. On my XAMPP instance i have installed Composer and ASN1 and X509 libraries.
For all, this is my code with some changes for take content form file (I thought maybe it would work, but it doesnt) :
<?php
require_once('C:\Windows\System32\vendor\autoload.php');
use Sop\ASN1\Type\Constructed\Sequence;
use Sop\ASN1\Element;
use Sop\X509\Certificate\Certificate;
$currentFile = 'C:\xampp\htdocs\ArchiTW\upload\kprocajlo\dokumenty\test.pdf';
$content = file_get_contents($currentFile);
file_put_contents('C:\xampp\htdocs\ArchiTW\upload\kprocajlo\dokumenty\text.txt',$content);
$txt='C:\xampp\htdocs\ArchiTW\upload\kprocajlo\dokumenty\text.txt';
$regexp = '/ByteRange\ \[\s*(\d+) (\d+) (\d+)/'; // subexpressions are used to extract b and c
//$regexp = '#ByteRange\s*\[(\d+) (\d+) (\d+)#';
$result = [];
$abc=preg_match_all($regexp, $txt, $result);
//$result[2][0] and $result[3][0] are b and c
if (isset($result[2]) && isset($result[3]) && isset($result[2][0]) && isset($result[3][0])) {
$start = $result[2][0];
$end = $result[3][0];
if ($stream = fopen($currentFile, 'rb')) {
$signature = stream_get_contents($stream, $end - $start - 2, $start + 1); // because we need to exclude < and > from start and end
fclose($stream);
}
$binaryData = hex2bin($signature);
$seq = Sequence::fromDER($binaryData);
$signed_data = $seq->getTagged(0)->asExplicit()->asSequence();
// ExtendedCertificatesAndCertificates: https://tools.ietf.org/html/rfc2315#section-6.6
$ecac = $signed_data->getTagged(0)->asImplicit(Element::TYPE_SET)->asSet();
// ExtendedCertificateOrCertificate: https://tools.ietf.org/html/rfc2315#section-6.5
$ecoc = $ecac->at($ecac->count() - 1);
$cert = Certificate::fromASN1($ecoc->asSequence());
$commonNameValue = $cert->tbsCertificate()->subject()->toString();
$StatusMsg = $commonNameValue;
echo $commonNameValue;
}

How to use correctly JSON.stringify with an PHP returned JS object

I have a php script which executes a python script and I got back an object like this:
{'data': [{'article title', 'article description', 'timestamp', 'weburl'}], 'status': 200, 'answers': [1]}
As I know I have to transform this into a javascript JSON from a javascript object type.
And I tried like
myjs = JSON.parse(JSON.stringify(answer))
and
JSON.stringify(answer)
or even just concatenate with "on the beginning and at the end. But neither got me a good result. So what is the correct way? or should I change something on php side?
The php part is simply this:
if ($_GET['times'] == 0) {
$command = escapeshellcmd('python3 feed.py '. $_GET['subject']);
$output = json_encode(shell_exec($command));
header('Content-type: application/json');
echo $output;
}
This is in my python script:
#!/usr/bin/python
import requests
import json
import html
import sys
requestpost = requests.post('NewsSource')
response_data = requestpost.json()
data = []
status = 0
answers = 0
out = {"data":[], "status":[], "answers":[0]}
searchterm = sys.argv[1]
error = 0
if requestpost.status_code == 200:
out["status"] = 200
for news in response_data["news"]:
try:
currentNews = json.loads(news)
if ((html.unescape(currentNews["title"]) != "Array" and html.unescape(currentNews["title"]).lower().find(searchterm.lower()) != -1) or (html.unescape(currentNews["description"]).lower().find(searchterm.lower()) != -1)):
outnews = {html.unescape(currentNews["timestamp"]), html.unescape(currentNews["title"]), html.unescape(currentNews["description"]), html.unescape(currentNews["link"])}
out["data"].append(outnews)
out["answers"][0] = out["answers"][0] +1
except:
error += 1
else:
out["status"] = 404
print (out)
Change the Python script so it prints JSON instead of Python format.
print(json.dumps(out))
However, sets aren't in JSON, so change outnews to a list.
outnews = [html.unescape(currentNews["timestamp"]), html.unescape(currentNews["title"]), html.unescape(currentNews["description"]), html.unescape(currentNews["link"])]
Then the PHP script can simply return that to the client.
if ($_GET['times'] == 0) {
$command = escapeshellcmd('python3 feed.py '. $_GET['subject']);
header('Content-type: application/json');
passthru($command);
}
If passthru() isn't working, you can try with your original shell_exec(). You don't need to call json_encode() because it's already encoded.
if ($_GET['times'] == 0) {
$command = escapeshellcmd('python3 feed.py '. $_GET['subject']);
$output = shell_exec($command);
header('Content-type: application/json');
echo $output;
}
Also If I want to get back all news than change out and return it back like this:
out = []
error = 0
status = 0
nrOfResults = 0
if requestpost.status_code == 200:
status = 200
for news in response_data["news"]:
try:
currentNews = json.loads(news)
if ((html.unescape(currentNews["title"]) != "Array" and html.unescape(currentNews["title"]).lower().find(searchterm.lower()) != -1) or (html.unescape(currentNews["description"]).lower().find(searchterm.lower()) != -1)):
outnews = [html.unescape(currentNews["timestamp"]), html.unescape(currentNews["title"]), html.unescape(currentNews["description"]), html.unescape(currentNews["link"])]
out.append(outnews)
nrOfResults = nrOfResults +1
except:
error += 1
else:
status = 404
out.append(status)
out.append(nrOfResults)
#outnews = [html.unescape(currentNews["timestamp"]), html.unescape(currentNews["title"]), html.unescape(currentNews["description"]), html.unescape(currentNews["link"])]
print(json.dumps(out))
than the last element of js array will be a the number of results and the before one will be the status of the source link.

How can I call multiple window.location.href in one javascript function?

I am trying to parse multiple href's with one JavaScript function. When I unremark the alert, it works fine. I'm assuming it has something to do with timing but I'm not sure the best way to do this.
I have tried the sleep command to add some sort of pause but that did not work as I expected it.
function pName(selectObject) {
var x = selectObject.value;
var y = selectObject.value.length;
if (x === undefined) {
x = 97;
}
str = '1st page here=' + "'" + x + "'";
//alert(str);
window.location.href = str;
if (y == 0) {
nxt = '2nd page - 1';
} else {
nxt = '2nd page - 2';
}
//alert(nxt);
window.location.href = nxt;
}
It seems like you're trying to set window.location.href to go to str first, and then nxt. Once you navigate to page str, JavaScript will stop execution, and you will be unable to subsequently trigger the redirect to nxt; you cannot have one page navigate to two different pages one after the other.
The obvious solution would be to simply redirect from page 1 to page 3 (nxt) outright, completely ignoring / bypassing page 2 (str). However, if you explicitly want the user to visit both pages, you'll need to set up an automatic redirect on page 2 (str) itself to take you to nxt.
This can be done by simply setting window.location.href = nxt on page 2 (str), though keep in mind that you'll actually need to transfer the logic of setting what nxt evaluates to over to page 2 (str) instead of having it on the initial page 1.
I was able to get this to work using onInput and handling the 2nd piece as it's own function.
onchange="pName(this);sendnew();return false;" onInput="sData(this);sendnew();return false;"
function pName(selectObject) {
var x = selectObject.value;
if (x === undefined) {
x = 97;
}
str = 'Command 1'+ "'" + x + "'" ;
//alert(str);
window.location.href = str;
}
function sData (selectObject) {
var y = selectObject.value.length;
if (y == 0) {
window.location.href = 'Command 2 - B' ;
} else {
window.location.href = 'Command 2 - B' ;
//alert(str);
};
}

How to supply the string created as a results of PHP to my javascript

I want to create a word check script in the input field that i have specified on the variable selector. The list of the words are pulled from the database. I have provided the query for the database. The results from the database are
>Array
>(
>[0] => Skype
>[1] => Phone
>[2] => Whatsapp
>[3] => Mobile
>[4] => Gmail
>[5] => email
>[6] => viber
>)
I am creating the string for the if statement inside my javascript using these above words. The result of $a is
$(selectors)[0].value.search(/Skype/i) !== -1 || $(selectors)
[0].value.search(/Phone/i) !== -1 || $(selectors)
[0].value.search(/Whatsapp/i) !== -1 || $(selectors)
[0].value.search(/Mobile/i) !== -1 || $(selectors)>>
[0].value.search(/Gmail/i) !== -1 || $(selectors)
[0].value.search(/email/i) !== -1 || $(selectors)
[0].value.search(/viber/i) !== -1
After that i tried to pass this string as a conditions in the script and it will execute the alert every time. I want it to execute only when the words match.
I have already tried writing
$(selectors)[0].value.search(/Skype/i) !== -1 || $(selectors)
[0].value.search(/Phone/i) !== -1 || $(selectors)
[0].value.search(/Whatsapp/i) !== -1 || $(selectors)
[0].value.search(/Mobile/i) !== -1 || $(selectors)
[0].value.search(/Gmail/i) !== -1 || $(selectors)
[0].value.search(/email/i) !== -1 || $(selectors)
[0].value.search(/viber/i) !== -1
inside the if statement and it works perfectly fine, But the reason I want to do this is I don,t want to come back to the code and add another line inside the if statement every time i want to add the word
<?php
//testing
$words = array();
$a='';
foreach($db->getRecordSet('SELECT * FROM conversationKeywords WHERE conStatus = :conStatus',array(':conStatus'=>1)) as $results){
array_push($words,$results['conKeyWord']);
}
/* //DEVELOPER DEBUGGIN PURPOSES ONLY, UNCOMMENT ON DEVELOPER MACHINE
echo '<pre>';
print_r($words);
echo '</pre>';
*/
foreach($words as $values){
if(!next($words)) {
$a.= '$(selectors)[0].value.search(/'.$values.'/i) !== -1';
}
else{
$a.= '$(selectors)[0].value.search(/'.$values.'/i) !== -1 || ';
}
}
//echo $a;
?>
<script>
var selectors = "#msg_text,#Message_Text,#job-desc";
var conditions = <?php echo json_encode($a) ?>;
console.log(conditions);
$("body").on("keyup",selectors,function(conditions){
if(warning !== true){
//var v = $('#msg_text').val();
if (conditions){
//alert("Warning! For safety and quality assurance, Please note that we kindly request all parties to communicate only through us.");
alertify
.alert("Warning!","For safety and quality assurance,we kindly request that all parties communicate ONLY through us.", function(){
alertify.message('OK');});
//warning = true;
}
}
});
</script>
Instead of writing $(selectors)[0].value.search(/SEARCHTERM/i) !== -1 over and over again for each search term I recommend to use regex alteration:
$(selectors)[0].value.search(/(SEARCHTERM_1|SEARCHTERM_2|SEARCHTERM_3)/i) !== -1
You can use PHP implode function to create the string of the search terms from your $words variable. Also you should use $(this).val() instead of $(selectors)[0].value if you want to get the value of the currently focused input element.
Your complete code should be like:
<?php
//testing
$words = array();
foreach($db->getRecordSet('SELECT * FROM conversationKeywords WHERE conStatus = :conStatus',array(':conStatus'=>1)) as $results){
$words[] = $results['conKeyWord'];
}
?>
<script>
var selectors = "#msg_text, #Message_Text, #job-desc";
$("body").on("keyup", selectors, function(){
if ($(this).val().search(/(<?= implode("|", $words) ?>)/i) !== -1) {
alertify.alert("Warning!","For safety and quality assurance,we kindly request that all parties communicate ONLY through us.", function(){
alertify.message('OK');
});
}
}
</script>
Note: $words[] = $results['conKeyWord']; is same as array_push($words,$results['conKeyWord']);, but it's faster and cleaner.

Passing sort order as a parameter

Referring to the sample SQL statement below. I'm able to pass parameter values to the placeholder '?' in the statement. However I'm wondering whether it is possible to pass in the sort order in the same way?
So instead of this:
//Create SQL query
var getAccountsTransactionsStatement = WL.Server.createSQLStatement(
"SELECT transactionId, fromAccount, toAccount, transactionDate, transactionAmount, transactionType " +
"FROM accounttransactions " +
"WHERE accounttransactions.fromAccount = ? OR accounttransactions.toAccount = ? " +
"ORDER BY transactionDate DESC " +
"LIMIT 20;"
);
Can I have this:
//Create SQL query
var getAccountsTransactionsStatement = WL.Server.createSQLStatement(
"SELECT transactionId, fromAccount, toAccount, transactionDate, transactionAmount, transactionType " +
"FROM accounttransactions " +
"WHERE accounttransactions.fromAccount = ? OR accounttransactions.toAccount = ? " +
"ORDER BY ? DESC " +
"LIMIT 20;"
);
And to invoke it:
//Invoke prepared SQL query and return invocation result
function getAccountTransactions1(accountId){
return WL.Server.invokeSQLStatement({
preparedStatement : getAccountsTransactionsStatement,
parameters : [accountId, accountId, transactionDate]
});
}
Two things:
This query piece:
WHERE accounttransactions.fromAccount = ? OR accounttransactions.toAccount = ?
Could be replaced with this:
WHERE ? in (accounttransactions.fromAccount, accounttransactions.toAccount)
No you can't. Parameters are values - kind of static stuff - while column names are not. You could probably work around the issue somehow in limited way by using s.t. like this:
ORDER BY
CASE ?
WHEN 'transactionDate' THEN transactionDate
WHEN 'someotherdate' THEN someotherdate
ELSE DATE '2010-01-01'
END
Note however that's a messy construction. Also depending on the type of the database you're using you might want to cast all the columns into one data type i.e. string. so to_char(transactionDate,'yyyy-mm-dd hh24:mm:ss') might be in order but you need to ensure that the sorting is proper in your case (as number tend to mess stuff up like '2' > '13').

Categories