Kohana: https issue for Rendering image - php

I am working for the module to export data with xls including pie and bar chart. i have develop this and working very fine on http. but it shows me "Internal Server error" while i run this on secure server https. i found the issue in URL::site most probably please check my code and let me know where i need to take care?
Session::instance()->set('graph_data', $graph_data_list);
foreach ($graph_data_list as $graph_data_key => $graph_data)
{
if ($graph_data['meta']['type'] === 'pie')
{
$$graph_data_key = Spreadsheet_Image::factory()
->worksheet($ws->get_active_sheet())
->source(
GenImage::instance('png')
->render(URL::site('admin/export/graph/'.$graph_data_key, $protocol), array(
'--width ' . Arr::path($graph_data, 'size.0', $pie_width),
'--cookie ' . Session::instance()->name() . ' ' . urlencode(Session::instance()->id()),
))
->output(GenImage::STRING)
)
->resizeProportional(false)
->width(Arr::path($graph_data, 'size.0', $pie_width) * $graph_width_multiply)
->height(Arr::path($graph_data, 'size.1', $pie_height) * $graph_height_multiply)
->coordinates($graph_data['meta']['cell']);
}
}
$protocol is either http or https(issue).

Related

Php tracking own location gives a randomized IP

-- Please scroll down to where I marked the PHP --
To explain in better detail.
I made a Leaflet map and in that map I want to load my own location.
Here's my code for that in Javascript, but this is out of question like #Pocketsand and I already discussed. So then scroll down to the PHP code and see if you can get the IP address through the browser.
$part_content = "<div id=\"mapid\"></div>";
//.setView([".$longitude.", ".$latitude."], ".$zoom_factor.");
$part_content .= "<script>
var map = L.map('mapid').fitWorld();
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
id: 'mapbox.streets'
}).addTo(map);
function onLocationFound(e) {
var radius = e.accuracy / 2;
L.marker(e.latlng).addTo(map)
.bindPopup(\"You are within \" + radius + \" meters from this point\").openPopup();
L.circle(e.latlng, radius).addTo(map);
}
function onLocationError(e) {
alert(e.message);
}
map.on('locationfound', onLocationFound);
map.on('locationerror', onLocationError);
map.locate({setView: true, maxZoom: 16});
</script>";
It's the same code as in this maps source code.
When I go to Firefox, it partly works and on someone else's computer it works fine, when on my computer I get the error from the image I showed you.
So I can't locate on my computer to my own location, as in google maps it works perfectly and my extensions also don't seem to block that part.
PHP:
Basically this:
$ip = !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
Gives me a random IP, because of HTTP_X_FORWARDED_FOR and REMOTE_ADDR gives me the correct IP, but not when I use this from a different IP address then the local one... thats why I check if the proxy is not empty.
This is the full php code for the tracker:
$ip = !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
$url = "http://freegeoip.net/json/$ip";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$data = curl_exec($ch);
curl_close($ch);
if ($data) {
$location = json_decode($data);
$longitude = $location->longitude;
$latitude = $location->latitude;
$longitude = str_replace(",", ".", $longitude);
$latitude = str_replace(",", ".", $latitude);
}
My current problem is:
$ip = $_SERVER['HTTP_CLIENT_IP'] ? $_SERVER['HTTP_CLIENT_IP'] : ($_SERVER['HTTP_X_FORWARDE‌​D_FOR'] ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']);
Which gets the correct IP address, but it almost seems like it gets the IP hosts location. Which is not my intention, I intend to get the clients location through the IP address, which currently isn't working.
I tried and tried, but couldn't seem to figure this out and hope you guys know more about this.
Thanks in advance!
I am guessing you didn't visit the URL in the error message? It's a Chrome security thing, try running off a local webserver or getting a https certificate on your remote server.
The Chrome Security team and I propose that, for new and particularly
powerful web platform features, browser vendors tend to prefer to make
the the feature available only to secure origins by default.
[...]
Definitions:
“Secure origins” are origins that match at least one of the following
(scheme, host, port) patterns:
(https, *, *)
(wss, *, *)
(*, localhost, ) (, 127/8, *)
(*, ::1/128, *)
(file, *, —)
(chrome-extension, *, —)
This list may be incomplete, and may need to be changed.
Source: https://www.chromium.org/Home/chromium-security/prefer-secure-origins-for-powerful-new-features
To get a client public ip address, in PHP 5.3 or greater use:
<?php
$ip = getenv('HTTP_CLIENT_IP')?:
getenv('HTTP_X_FORWARDED_FOR')?:
getenv('HTTP_X_FORWARDED')?:
getenv('HTTP_FORWARDED_FOR')?:
getenv('HTTP_FORWARDED')?:
getenv('REMOTE_ADDR');
?>
And if that is not working, use an external provider like https://geolocation-db.com
A JSON-P callback example:
<?php
$jsonp = file_get_contents('https://geolocation-db.com/jsonp');
$data = jsonp_decode($jsonp);
print $data->IPv4 . '<br>';
print $data->country_code . '<br>';
print $data->country_name . '<br>';
print $data->state . '<br>';
print $data->city . '<br>';
print $data->postal . '<br>';
print $data->latitude . '<br>';
print $data->longitude . '<br>';
// Strip callback function name and parenthesis
function jsonp_decode($jsonp) {
if($jsonp[0] !== '[' && $jsonp[0] !== '{') {
$jsonp = substr($jsonp, strpos($jsonp, '('));
}
return json_decode(trim($jsonp,'();'));
}
?>
And a JSON example:
<?php
$json = file_get_contents('https://geolocation-db.com/json');
$data = json_decode($json);
print $data->country_code . '<br>';
print $data->country_name . '<br>';
print $data->state . '<br>';
print $data->city . '<br>';
print $data->postal . '<br>';
print $data->latitude . '<br>';
print $data->longitude . '<br>';
print $data->IPv4 . '<br>';
?>
Instead of going with a PHP function I did a leaflet function instead, which tracks the user through the browser.
Using the library: leaflet.locate
Where then I could use the:
// create control and add to map
var lc = L.control.locate().addTo(map);
// request location update and set location
lc.start();
But this isn't the answer to the PHP part of my code, even though this leaflet function also works for now.
Sadly the PHP part can't find the exact address through the IP if the server is at another place, but the leaflet way of doing it through the browser does work. Hope you guys find use in these answers.

PHP - URL gets malformed during redirect

So, I have an image link that has this href:
http://www.app.com/link?target=www.target.com&param1=abc&param2=xyz
This is processed like so (I use laravel):
function out (Request $request) {
$url = $request->target;
$qs = $request->except('target');
if ( !empty($qs) ) {
$url .= strpos($url, '?') !== false ? '&' : '?';
$url .= http_build_query($qs);
}
return redirect($url);
}
Most of the time, this works. However, lately, we've been experiencing an issue where param1 and param2 are attached to the URL in a seemingly infinite loop causing us to hit a 414 Request URI too long Error.
The problem is that it happens so randomly that I really don't know where to check because I added a checker before the return statement.
if ( substr_count($url, 'param1') > 1 ) {
$file = storage_path() . '/logs/logger.log';
$log = "[ " . date("d-m-Y H:i:sa") . " ] [ {$request->ip()} ] - {$url} \n";
file_put_contents($file, $log, FILE_APPEND);
}
And it hasn't logged a single hit. Even after our testers experienced the bug.
Is it possible that the receiving application is breaking the URL somehow?
What information should I be looking out for? Have you seen an issue like this before?
Is it the http_build_query that could be causing this and that my checker just doesn't work as expected (though, I did test it and it logged my test URL).
Any help on the matter would be great.
Assuming and issue with http_build_query:
Well, one attempt you may try is to rewrite the code without $request->except and http_build_query.
If you don't have any special reason to use http_build_query i would suggest to use $request->input.
Example with $request->input:
function out (Request $request) {
$url = $request->target;
$param1 = $request->input('param1', '');
$param2 = $request->input('param2', '');
if (!empty($param1) || !empty($param2)) {
$url .= '?';
}
if (!empty($param1) && !empty($param2)) {
$url .= 'param1=' . $param1 . '&param2=' . $param2;
} else {
$url .= !empty($param1) 'param1=' . $param1 : '';
$url .= !empty($param2) 'param2=' . $param2 : '';
}
return redirect($url);
}
The solution is a little bit more verbose but with that, you should be sure 100% that is not the code to generate the redundancy.
Absurd, remote possibility:
The second thing I would try is to check you log system. For instance if you are running under apache you should have a file called access.log under /var/log/apache2/ (or under /var/log/nginx/ with nginx).
In there you should have the history of all your http requests.
Maybe there is a chance that some of the wired requests with multiple params are from a strange IP address.
If this is the case, it means that some company is monitoring and testing the website (potentially with the strange parameters) for security reasons.
If this is the case, I guess you are under http and you should switch to https.
Anyway, with the new code, you should be sure about the code and be able to investigate any other part of the system.

Laravel sessions keep regenerating after upload to live server

I have recently deployed my new website to a shared hosting server.
I had to change some paths in order for it to work but in the end I got it all working, except for sessions.
The website behaves as if sessions are completely disabled. Upon closer inspection, using the "file" driver for sessions it creates many sessions in the storage/sessions folder.
I changed to the "database" driver and there was similar behaviour, many new rows/sessions being created after every page operation.
Does anyone have any idea what could be causing this?
Here's an example of one function that sets session variables:
public function addItem($itemId) {
if (Session::get('cart.' . $itemId) !== null) {
$quantity = Session::get('cart.' . $itemId) + Input::get('quantity');
} else {
$quantity = Input::get('quantity');
}
if (!Input::get('quantity'))
$quantity = Session::get('cart.' . $itemId) + 1;
Session::set('cart.' . $itemId, $quantity);
$plural = (Input::get('quantity') > 1 ? Lang::get('messages.units') : Lang::get('messages.unit'));
$msg = Input::get('quantity') . ' ' . $plural . ' '.Lang::get('messages.addedtocart').'!';
if (Request::ajax()) {
return Response::json(['quantity' => $quantity, 'message' => $msg]);
} else {
return Redirect::back()->with('message', $msg);
}
}
I have found out what it is.
It appears that for some reason my ISP is stopping my sessions from working for whatever reason.
I switched to a VPN and all of a sudden all sessions work again. I noticed that other web apps like Google and SO were also behaving strangely.
Has anyone else encountered this before?

Upload Files to Sharepoint Library through WS with PHP (NTLM & ThyBag)

I use the Lists-WS from Sharepoint to retrieve information about DocumentLibraries and the files in these Libraries. Now I want to upload new files. How do I implement uploads with PHP? Till now I use Thybag SharePointAPI to get information (Link).
(the SharepointServer uses NTLM-Authentication)
THX in advance!!
UPDATE:
I want to call the Copy.asmx WS from sharepoint. To do so, I use the following lines:
$sourceurl = 'http://null';
$params = '
<CopyIntoItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<SourceUrl>'.$sourceurl.'</SourceUrl>
<DestinationUrls>' . $destinationURLs . '</DestinationUrls>
<Stream>' . $stream . '</Stream>
</CopyIntoItems>
';
$xmlvar = new \SoapVar($params, XSD_ANYXML);
// Attempt to run operation
try {
$result = $this->soapClient->CopyIntoItems($xmlvar)->CopyIntoItemsResponse->CopyIntoItemsResult;
} catch (\SoapFault $fault) {
$this->onError($fault);
}
But I dont even get any response ($result == NULL).....
You can use SPServices' CopyIntoItems method. You can find a detailed conversation here containing the details on using the CopyIntoItems service to upload a document.

New Zend added controllers stopped working showing error 500 for New Controllers, Previous Controllers Working fine

My Zend application was running fine until today, when I changed something( i mean literally nothing) which caused new controllers to stop working. I have debugged every part of the code but I can not find any traces as to why is it happening!
My Previous added controls are working, and new actions added to those also,
but new added controls dont work.
Error is this:
HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request.
same situation like this question:
Zend Error controller stopped working for 500
Any body having a solution! Please Reply,
I replaced every bit , of apache ,zend ,php library sources with new one, but with no success.
I don't think you have enough logging going on to troubleshoot this. Do you have a fatal error handler? Here is one that should help you see what's going on (Add to Boostrap class). Basically, it logs fatal errors to a log file and displays a static html page to the user.
/**
* Fatal Error Catcher which runs as a registered shutdown function
*/
public static function fatalErrorCatcher() {
$error = error_get_last();
if ($error && (
$error['type'] === E_ERROR ||
$error['type'] === E_COMPILE_ERROR ||
$error['type'] === E_CORE_ERROR ||
$error['type'] === E_PARSE
)) {
// kill the buffer content, it's broken anyway
while (ob_get_level()) {
ob_end_clean();
}
// make a summary of the error
$errorSummary = date('m/d/Y G:i:s') . ' '
. $error['message'] . ' on file ' . $error['file'] . ':' . $error['line'] . ' URL:'
. $_SERVER["SERVER_NAME"]
. ($_SERVER["SERVER_PORT"] != "80" ? ":" . $_SERVER["SERVER_PORT"] : "")
. $_SERVER["REQUEST_URI"] . "\n";
// log the error to file
file_put_contents('/var/log/fata-errors.log', $errorSummary, FILE_APPEND | LOCK_EX);
// tell the user we're sorry
header('HTTP/1.1 500 Internal Server Error');
echo file_get_contents('/var/www/html/fail-whale.html');
}
}
AND You register it in bootstrap as early in the init as possible:
register_shutdown_function(array('Bootstrap', 'fatalErrorCatcher'));

Categories