having trouble incorporating css into perl cgi - css

the code below is a cgi file and I am having problems displaying the image and style from an external css file. The code is in lines 18-28 and I'm not sure what I am doing wrong. I would appreciate any help.
#!/usr/bin/perl -w
use strict;
use DBI;
use CGI;
use CGI::Carp('fatalsToBrowser');
my $query = new CGI;
print $query->header();
my $my_database = "TrypSnoDB";
my $localhost = "localhost";
my $dsn = "DBI:mysql:$my_database:$localhost";
my $db_user_name = "adrian";
my $db_password = "temp_pass";
my $dbh = DBI->connect("DBI:mysql:database=TrypSnoDB;host=localhost;mysql_socket=/private/software/mysql/mysql.sock","adrian","temp_pass", {'RaiseError' => 1});
print "<html>\n";
print "<head>\n";
print "<title>Welcome to the T. Brucei snoRNA Database</title>\n";
print "<link type='text/css' rel='stylesheet' href='/public_html/style.css'>\n";
print "</head>\n";
print "<body>\n";
print "<h1>Trypanosomatid snoRNA Database</h1>\n";
print "<img class='my_images' src='/public_html/tb_pic1.png'>\n";
print "</body>\n";
print "</html>\n";
if ($query->param('submit1')){
my $orig_sno = $query->param('snorna1');
my $family = $query->param('family1');
my $query_type = $query->param('target_option1');
my $target = $query->param('target_name1');
if ($orig_sno eq "Trypanosoma brucei") {
$orig_sno = 1;
}
elsif ($orig_sno eq "Leishmania major") {
$orig_sno = 7;
}
elsif ($orig_sno eq "ALL") {
$orig_sno = "1 or ST.org_id=7";
}
if ($family eq "ALL") {
$family = "'C/D' or ST.family='H/ACA'";
}
else {
$family = "'$family'";
}
if ($target ne "ALL") {
$family = "$family and T.target_name='$target'";
}
my($db_query,$common_tar,$exp_ver_sno,$exp_ver_tar,$total);
$db_query = "SELECT ST.sno_name,T.target_name,T.location,T.base_pair,SM.annotated_seq FROM sno_Table ST,sno_Modifications SM,Targets T WHERE ST.sno_id=SM.sno_id and SM.mod_id=T.target_id and (ST.org_id=$orig_sno) and (ST.family=$family)";
$common_tar="and T.target_id in(SELECT T.target_id FROM sno_Table ST,sno_Modifications SM,Targets T WHERE ST.sno_id=SM.sno_id and SM.mod_id=T.target_id group by T.target_id having count(*)=2) order by T.location desc";
$exp_ver_sno="and ST.exper_ver='Y'";
$exp_ver_tar = "and T.exp_ver='Y'";
if ($query_type eq "snoRNAs with common targets") {
$db_query=$db_query.$common_tar;
}
elsif ($query_type eq "Experimentally verified snoRNAs") {
$db_query=$db_query.$exp_ver_sno;
}
elsif ($query_type eq "snoRNAs with experimentally verified targets") {
$db_query=$db_query.$exp_ver_tar;
}
elsif ($query_type eq "ALL"){
$db_query=$db_query;
}
my $sth = $dbh->prepare($db_query);
$sth->execute();
my$total = $sth->rows;
print "<table border=1>\n
<tr>
<th>snoRNA</th>\n
<th>Target Name</th>\n
<th>Target Location</th>\n
<th>Target Base Pair</th>\n
<th>Annotated Sequence</th>\n
</tr>\n";
while (my#row = $sth->fetchrow_array()){
my$sno_name = $row[0];
my$tar_name = $row[1];
my$tar_loc = $row[2];
my$tar_bp = $row[3];
my$annotated_seq = $row[4];
print "<tr>\n<td>$sno_name</td><td>$tar_name</td><td>$tar_loc</td><td>$tar_bp</td><td>$annotated_seq</td></tr>\n";
}
print "<tr>
<th>TOTAL</th>\n
<th>$total</th>\n
</tr>\n";
print "</table>";
}

Your problem is almost certainly that you have the wrong URL for the CSS file. You can confirm that by looking in the web server error log and seeing if there is a 404 record for the CSS request.
Unfortunately I can't tell you what the correct URL is as I have no idea how your web server is configured.
There are a couple of other issues that you might want to address though:
The HTML that you generate is invalid. You print the tags outside of the and tags. Printing raw HTML within your Perl program is a terrible idea - it's far too easy to make the kinds of errors that you have here. You would be far better advised to use a templating engine (I recommend the Template Toolkit).
Your database queries are prone to SQL injection attacks. Please switch to using bind variables before someone trashes your server.

this is in response to Dave Cross comment regarding the SQL statement building. To convert the statement build to use bindings appears to be fairly straightforward in order to prevent an SQL injection.
To use placeholder bindings I think the OP only needs to replace the variables $orig_sno and $family in the $db_query variable with the ? character. like so:
$db_query = "SELECT ST.sno_name,T.target_name,T.location,T.base_pair,SM.annotated_seq
FROM sno_Table ST,sno_Modifications SM,Targets T WHERE ST.sno_id=SM.sno_id and
SM.mod_id=T.target_id and (ST.org_id=?) and (ST.family=?)"; # one line
...
my $sth = $dbh->prepare($db_query);
$sth->execute($orig_sno, $family);
However as the $family variable is built possibly out of a previous conditional, a further variable $target is also in play.
if ($family eq "ALL") {
$family = "'C/D' or ST.family='H/ACA'";
}
else {
$family = "'$family'";
}
if ($target ne "ALL") {
$family = "$family and T.target_name='$target'";
}
Will the placeholder handle this interpolated variable? Or would the $target variable also require its own placeholder?
And is this all that would be required to do to deter would be SQL injection attacks in this case?
solved. If the $target variable did require its own place holder, a few adjustments to the conditionals would do the trick.
else {
$family = "'$family'";
}
# removed - if $target ne ALL conditonal
my($db_query,$common_tar,$exp_ver_sno,$exp_ver_tar,$total);
$db_query = "SELECT ... and (ST.org_id=?) and (ST.family=?)";
if ($target ne "ALL") {
$db_query =~ s/\)$//;
$db_query .= ' and T.target_name=?)';
}
$common_tar="and T.target_id ... ";
...
my $sth = $dbh->prepare($db_query);
if ($target ne 'ALL'){
$sth->execute($orig_sno, $family, $target);
else{
$sth->execute($orig_sno, $family);
}

Related

How to resolve this error? Use of uninitialized value $val1 in printf at sham.pl line 112

This is my script. Please suggest how to avoid the error. This script worked fine while using other files.
`if (($line1 =~ /^[##]/) || ($line2 =~ /^[##]/)) {
# do nothing, it's a comment - probably not necessary after above cleanup
} else {
my #data1 = split(" ", $line1);
my #data2 = split(" ", $line2);
my $time = $data1[0];
my $val1 = $data1[$d1];
my $val2 = $data2[$d2];
printf OUT "%8.3f\t%f\t%f\n", $time, $val1, $val2;
}
}
close(OUT);
exit;
I have not tried anything since I am new to perl and have less knowledge about it.

phpexcel PHPExcel_Shared_Date::isDateTime not working

the file is xlsx and the column format is date MM-DD-YYYY
I have tried several different ways to determine if the value is a date.
PHPExcel_Shared_Date::isDateTime just is not working and do not know why. The data is being save in database and is showing the numbers as such:
41137
41618
42206
42076
41137
42206
41137
41988
my code:
$inputFileType = PHPExcel_IOFactory::identify($fullFilePath);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setReadDataOnly(false);
$objPHPExcel = $objReader->load($fullFilePath);
$objPHPExcel->setActiveSheetIndex(0);
$worksheetIndex = 1;
$worksheetName = '';
$actualRows = 0;
foreach($objPHPExcel->getWorksheetIterator() as $worksheet)
{
$lineNumber = 1;
$worksheetName = $worksheet->getTitle();
$columnSum = array();
foreach($worksheet->getRowIterator() as $row)
{
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true); // Loop all cells, even if it is not set = true else set to false
$columnNumber = 1;
foreach($cellIterator as $cell)
{
$dataValue = $cell->getCalculatedValue();
//$dataValue = $cell->getFormattedValue();
if(!empty($dataValue))
{
if(PHPExcel_Shared_Date::isDateTime($cell))
{
$dataValue = date('Y-m-d H', PHPExcel_Shared_Date::ExcelToPHP($dataValue));
}
else
{
// do something
}
}
}
}
}
Analysing the file, there's a few problems.... it doesn't validate cleanly under the Microsoft's Open XML SDK 2.0 productivity tool for MS Office.
Initial problem (which should trigger a loader error in PHPExcel) is the SheetView Zoom Scale, which should be a minimum value of 1. This problem can by "bypassed" by editing Classes/PHPExcel/Worksheet/SheetView.php and modifying the setZoomScaleNormal() method to avoid throwing the exception if the supplied argument value is out of range.
public function setZoomScaleNormal($pValue = 100)
{
if (($pValue >= 1) || is_null($pValue)) {
$this->zoomScaleNormal = $pValue;
// } else {
// throw new PHPExcel_Exception("Scale must be greater than or equal to 1.");
}
return $this;
}
The second problem is that custom number formats are defined with ids in the range 100-118, but all format ids below 164 are documented as reserved for Microsoft use. Excel itself is obviously more forgiving about breaking its documented rules.
You can resolved this by hacking the Classes/PHPExcel/Reader/Excel2007.php file and modifying the load() method, around line 512, by commenting out the check that tells PHPExcel to use the built-in number formats:
// if ((int)$xf["numFmtId"] < 164) {
// $numFmt = PHPExcel_Style_NumberFormat::builtInFormatCode((int)$xf["numFmtId"]);
// }
or
if ((int)$xf["numFmtId"] < 164 &&
PHPExcel_Style_NumberFormat::builtInFormatCodeIndex((int)$xf["numFmtId"]) !== false) {
$numFmt = PHPExcel_Style_NumberFormat::builtInFormatCode((int)$xf["numFmtId"]);
}
There are also issues with font size definitions, but these won't prevent the file from loading

PHPexcel - getOldCalculatedValue and rangeToArray

Searched for quite a while now, but I'm stuck at the following problem.
I am using PHPexcel 1.8.0
The spreadsheet is read using the following code:
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, TRUE);
So far ok and it works well.
But some spreadsheets contain external referenced data.
And for that I want to use "getOldCalculatedValue".
How do I combine "getOldCalculatedValue" with "rangeToArray" ?
Or is "rangeToArray" inappropriate for this ?
Thanks for any help or hints !
Simple answer, you can't combine the two
rangeToArray() is a simple method for a simple purpose, it doesn't try to do anything clever, simply to return the data from the worksheet as efficiently and quickly as possible
getOldCalculatedValue() is used for a very specific circumstance, and isn't guaranteed to be correct even then, because it retrieves the last value calculated for the cell in MS EXcel itself, which ,ay not be correct if the external workbook wasn't available to MS Excel in that circumstance, or MS Excel formula evaluation was disable.
When calculating cells values from a formula, the PHPExcel calculation engine should use the getOldCalculatedValue() as a fallback if it finds an external reference, and rangeToArray() will try to use this method, but it isn't perfect, especially when that reference in nested deep inside other formulae referenced in other cells.
If you know that a formula in a cell contains an external reference, you should use getOldCalculatedValue() directly for that cell
I came up with the following solution.
Maybe not perfect, but it currently does the job. Thanks for any improvements!
With PHPExcel included and the excel file uploaded and ready, I continue with:
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
Create a new array to store the cell values of a row
$arr_row = array();
Loop through the rows
for ($rownumber = 2; $rownumber <= $highestRow; $rownumber++){
$row = $sheet->getRowIterator($rownumber)->current();
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
Then loop through the cells of the current row
foreach ($cellIterator as $cell) {
Find cells with a formula
$cellcheck = substr($cell->getValue(),0,1);
if($cellcheck == '='){
$cell_content = $cell->getOldCalculatedValue();
}
else{
$cell_content = $cell->getValue();
}
Add the cell values to the array
array_push($arr_row,$cell_content);
Close cell loop
}
At this point I use the $arr_row to do further calculations and string formatting, before finally inserting it into a mysql table.
Close row loop
}
I made some changes in the function rangeToArray() inside Worksheet.php.
Worked fine!
public function rangeToArray($pRange = 'A1', $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) {
// Returnvalue
$returnValue = array();
// Identify the range that we need to extract from the worksheet
list($rangeStart, $rangeEnd) = PHPExcel_Cell::rangeBoundaries($pRange);
$minCol = PHPExcel_Cell::stringFromColumnIndex($rangeStart[0] -1);
$minRow = $rangeStart[1];
$maxCol = PHPExcel_Cell::stringFromColumnIndex($rangeEnd[0] -1);
$maxRow = $rangeEnd[1];
$maxCol++;
// Loop through rows
$r = -1;
for ($row = $minRow; $row <= $maxRow; ++$row) {
$rRef = ($returnCellRef) ? $row : ++$r;
$c = -1;
// Loop through columns in the current row
for ($col = $minCol; $col != $maxCol; ++$col) {
$cRef = ($returnCellRef) ? $col : ++$c;
// Using getCell() will create a new cell if it doesn't already exist. We don't want that to happen
// so we test and retrieve directly against _cellCollection
if ($this->_cellCollection->isDataSet($col.$row)) {
// Cell exists
$cell = $this->_cellCollection->getCacheData($col.$row);
if ($cell->getValue() !== null) {
if ($cell->getValue() instanceof PHPExcel_RichText) {
$returnValue[$rRef][$cRef] = $cell->getValue()->getPlainText();
} else {
if ($calculateFormulas)
{ ##################################### CHANGED LINES
if(!preg_match('/^[=].*/', $cell->getValue()))
{
$returnValue[$rRef][$cRef] = $cell->getCalculatedValue(); # THE ORIGINAL CODE ONLY HAD THIS LINE
}
else
{
$returnValue[$rRef][$cRef] = $cell->getOldCalculatedValue();
}
} ##################################### CHANGED LINES
else
{
$returnValue[$rRef][$cRef] = $cell->getValue();
}
}
if ($formatData) {
$style = $this->_parent->getCellXfByIndex($cell->getXfIndex());
$returnValue[$rRef][$cRef] = PHPExcel_Style_NumberFormat::toFormattedString(
$returnValue[$rRef][$cRef],
($style && $style->getNumberFormat()) ?
$style->getNumberFormat()->getFormatCode() :
PHPExcel_Style_NumberFormat::FORMAT_GENERAL
);
}
} else {
// Cell holds a NULL
$returnValue[$rRef][$cRef] = $nullValue;
}
} else {
// Cell doesn't exist
$returnValue[$rRef][$cRef] = $nullValue;
}
}
}
// Return
return $returnValue;
}

Unsufficient privileges from responseText in Plone4.3

I use PloneBooking3.0.0a2 with Plone4.3.3, but if I want to show periodic bookings I get an unsufficient privileges error. In my opinion there are two functions responsible for that:
function showPeriodicityResult(url, alt_url, target_id, form_id, waiting_text) {
ajaxobject = getXmlHttpRequest();
form = document.getElementById(form_id);
periodicity_type = getPeriodicityType(form);
periodicity_end_date = form['periodicity_form_periodicity_end_date_0'].value;
periodicity_variable = form['periodicity2_x'].value;
query = getPeriodicityQuery(periodicity_type, periodicity_end_date, periodicity_variable);
url = url + query + "&d=" + (new Date()).getTime();
alt_url = alt_url + query;
// Opera does not support ajax
if (ajaxobject == null) {
window.location = alt_url;
} else {
var node = document.getElementById(target_id);
node.innerHTML = waiting_text;
ajaxobject.open('GET', url, true);
ajaxobject.onreadystatechange = function(){CallBackGenerateAjaxHTML(ajaxobject, target_id);};
ajaxobject.send(null);
}
}
and
function CallBackGenerateAjaxHTML(ajaxobject, target_id) {
if (ajaxobject.readyState == 4) {
if (ajaxobject.status > 299 || ajaxobject.status < 200) {
return;
}
elem = document.getElementById(target_id);
elem.innerHTML = ajaxobject.responseText;
}
}
Especially the innerHTML setting with responseText seems to be a problem. Is there is a quick answer like Plone version diff from 3 to 4 or must I work in-depth?
You mentioned in the comments that the portal.uid_catalog raises the Unauthorized.
When I recall correctly the uid-catalog requires a higher permission since the last Plone hotfix. But you also can search an Item when given a UID with the normal Catalog.
here_obj python:portal.portal_catalog(UID=here_uid)[0].getObject();
This way you should be able to get your Object.

Drupal Views:Add condition in where clause where the value is a field in hook_alter_query

I am trying to add a condition to a query like:
civicrm_contact_civicrm_relationship.id <> civicrm_contact_civicrm_relationship_1.id
but for the second field drupal takes it as a string so it always result into
civicrm_contact_civicrm_relationship.id <> 'civicrm_contact_civicrm_relationship_1.id'
I've tried to play with the numerical value with no success.
Any idea how can I do this? May be with another hook? any tip will be welcome!
My code:
$view->query->where[2]["conditions"][0]["field"] = "civicrm_contact_civicrm_relationship_1.id";
$view->query->where[2]["conditions"][0]["operator"] = "IS NULL";
$view->query->where[2]["conditions"][0]["value"] = "";
$view->query->where[2]["conditions"][1]["field"] = "civicrm_contact_civicrm_relationship.id";
$view->query->where[2]["conditions"][1]["operator"] = "IS NULL";
$view->query->where[2]["conditions"][1]["value"] = "";
$view->query->where[2]["conditions"][2]["field"] = "civicrm_contact_civicrm_relationship.id";
$view->query->where[2]["conditions"][2]["value"] ="civicrm_contact_civicrm_relationship_1.id";
$view->query->where[2]["conditions"][2]["numeric"] = "1";
$view->query->where[2]["conditions"][2]["operator"] = "<>";
$view->query->where[2]["type"] = "OR";
try something like
function my_hook_views_query_alter(&$view, &$query)
{
if ($view->name == 'my_hook') {
$alias = $query->add_table('civicrm_contact_civicrm_relationship','civicrm_contact_civicrm_relationship_1');
$query->add_where_expression(0,'civicrm_contact_civicrm_relationship.id <> civicrm_contact_civicrm_relationship_1.id');
dpm($query); //dumps object to admin with devel module
}
}

Resources