I created a function in PHP that downloads a map created in google maps, I am able to download, however, the route is not coming when I am saving.
How the picture is coming:
How it should come:
Code:
function download_remote_file_with_curl($file_url, $save_to) {
$arrContextOptions = array(
"ssl" => array(
"verify_peer" => false,
"verify_peer_name" => false,
),
);
$response = file_get_contents($file_url, false, stream_context_create($arrContextOptions));
//echo $response;
//file_put_contents($save_to, $response);
$downloaded_file = fopen($save_to, 'wb');
fwrite($downloaded_file, $response);
fclose($downloaded_file);
}
$urlDownload = "https://maps.googleapis.com/maps/api/staticmap?size=1000x1000&maptype=roadmap&path=enc:zklaAbqcyJzCmF~#b#fBdAzCiEnKyQlFpCnMdH~_#nU~JlFlCNrw#oL~IcApEZxd#nQpgBhq#tRtStgA``Aty#`o#ll#pa#tNhFzMvJfG~D|Y~Hxd#rMll#`Rtb#jLjNzExWtFz`#bJvM|ItG`LdF|V`GvD|CL|JiBv]aGld#cHrk#cLdU_Fpb#wGdMg#vaAqAti#g#z_#Cj~A{#raAfDlp#xAfYa#tyAuDtVEbTdApO`#rGk#dP`#vgEo#baCuA`|AaArHGIzAwCtHqDlNf#rl#lA~bAnAphAMj`#hBlj#\hd#s#tL\pHnCff#~A`|#lMnmEnBbKrFbDn`#jP~RtQ~k#hVhNtGb#xFgPheAsAnOuIlaBpj#|qCtDzGb`A~`AzDvGd#vI{Af_#x#~GxItHzLvGp\fLxc#t\pe#d`#h|AnmA`WvQnEDnF}Bd\uUjGeB~Gb#nEvB~KnMri#ni#fjCbfCpmArkAv|#pz#bjAjhApcEt}Ddx#pv#r_#lZzyB|hBtoHneGzZvVh|#xq#fb#jZh^fZjD~E`FlOzMbc#|L|`#hQrS~H`MhQ~w#hEdzB~B~hAbAbk#Ux^kNx~BeGriAaCbe#|#zSt#`ChDnBnZlAlFtCl`#`AzMpBpRvJlKvFbKlLxd#pcAdk#~oAjbAbiAnPxLfq#b^ndDpkBbdDfjBbqAdt#hFjAtNhCfMbD|g#tYhxDfxBrqFx~C|CpCzA|EE~E}i#raDsOb}#uO~{#{f#zvCr#hG~CdDf`Bly#hL|Lt#bClD|Brx#naAvAnAzb#lg#zj#veDjMbI|rBhdAlJzFdAjCbBpgBpMlsQdIhhO]p^?hb#z#dsAp#jo#l#pWffDp`FzyB~eDxdEhlGpNrSvv#hn#duEvuDnsJp~HtpLvvJ~bBtvAjw#hp#hDnFnHvpBlSh}FrFd_BvAno#tu#buTtPxwEnXvhJbRddGbQ~nGlNjqFlJv~BvC~rAdFppBvNhvEhShsGw#nQ}i#htBsq#lgCcJd]}BjPkG|y#gPptBu]byE_H~gArB`EfG|FxXnYfv#nv#nWhX`RjRjHj`#bfBdgKlCrKzGhQp`#lbAtdBnjEr_#z`A`~#n}Bth#fuAdpDzdJ|W`o#`ClAxIj#beA~A~p#bAx|F~I`lEzGvwAbCdMx#neDjlAbp#hUrE}#prB_qCzBaAjJAxOKhWfAfP?tm#}Q~{Bkr#r{EeyAxPoApfB~WzK|AHTdBDrO}A~RmBrXsCzZuA~NJx#bD|#dAfX`#{#nG&markers=color:green|label:A|-10.8819552,-61.95483539999998&markers=color:red|label:B|-12.457280801085,-64.2310285267651&key=yourkey";
download_remote_file_with_curl($urlDownload, realpath('C:/test') . '/' . 'test' . '.jpg');
?>
Thank you!
I don't know if what I'm about to write makes sense, but the route that you want to download is an item that appears once it's selected.
For example when the "SKIP" buttom in Youtube appears to quit an advertisement, it creates an instance of that box in HTML, and then it dissappears when Add is over.
I think that the route is this kind of instance and you must add a line of code to also take that piece of html
Related
I have a Leave application project that generates a PDF file.
this is the code that generates the pdf after I click submit.
$id = DB::table('leave')->where('user_id', auth()->user()->id)->max('id');
$data = leave::where('id', $id)->select('*')->get();
$filename = auth()->user()->name." - S - ". "LEAVE - ".$randomString->randomString(8)."-".$request->filing_date.".pdf";
$path = storage_path('app/leave_file/'.$filename);
PDF::loadView('pdf_views.leave_pdf', $data[0])->setPaper('legal')->save($path);
if(file_exists($path)){
DB::table('leave_files')->insert([
'filename' => $filename,
'leave_id' => DB::table('leave')->where('user_id', auth()->user()->id)->max('id'),
]);
}
return redirect()->route('leave')->with('success', "success");
I wonder if I can make the newly generated pdf open in the new tab after I click submit on my leave application. thank you to anyone who can help
According to the Laravel docs this is what you need: https://laravel.com/docs/9.x/responses#file-responses
File Responses
The file method may be used to display a file, such as an image or PDF, directly in the user's browser instead of initiating a download. This method accepts the path to the file as its first argument and an array of headers as its second argument:
return response()->file($pathToFile);
return response()->file($pathToFile, $headers);
Use the Cache Facade, to store the generated pdf temporary.
$uuid = Str::uuid();
return response()->stream(function () use ($uuid) {
echo Cache::remember($uuid, 300, function() {
return 'genertated pdf content'
});
}, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => sprintf('attachment; filename=%s;', $uuid),
]);
Create a route to access to cached file. Name the route.
Now you can open it in a new tab from you frontend e.g. Generate the route with route('routename', ['param' => 123]) and pass it to your FE with a REST endpoint for example.
window.open(url,'_blank');
I have created a plugin and after the other processes of the plugin are done i would like to redirect to a given url from a controller in the backend.
i have created a plugin that creates a documents from orders and that is working fine. however at the end of the process i would like to redirect to a url that can download or open the document that has been created. i know the url for doing so is structured like this (http://localhost:8000/backend/Order/openPdf?id=harshvalueforpdf). i am using shopware version 5.5.1 in docker on my local host.
public function redirectmyurlAction()
{
$harsh = "9ce6b9a9cd5d469386fbb5bd692f9644";
$search_word = $harsh;
error_log(print_r(array('Reached redirect action'), true)."\n", 3, Shopware()->DocPath() . '/test.log');
$this->redirect(
array(
'module'=> backend,
'controller' => 'Order',
'action' => 'openPdf?id='.$search_word,
)
);
}
i expect that when the process reached this action the user is redirected to the created url and then it should be able to download or show the pdf. But it logs the log i put before the redirect but does not redirect. nothing is logged in errors or console. When i put the same redirect on the frontend i get the CSRFTokenValidationException which is what i expect, but it shows the redirect works there so why not in the backend.
Update:
After the responses,i have copied the function and modified it as below but it logs everything there and still does nothing am i missing something?
public function openmyPdf($DocHarsh, $orderId)
{
error_log(print_r(array('Entered openmyPdf function',$DocHarsh,$orderId,$date), true)."\n", 3, Shopware()->DocPath() . '/error.log');
$filesystem = $this->container->get('shopware.filesystem.private');
$file = sprintf('documents/%s.pdf', basename($DocHarsh));
if ($filesystem->has($file) === false) {
error_log(print_r(array('Entered if statement, file doesnt exists ',$DocHarsh,$orderId,$date), true)."\n", 3, Shopware()->DocPath() . '/error.log');
$this->View()->assign([
'success' => false,
'data' => $this->Request()->getParams(),
'message' => 'File not exist',
]);
return;
}
// Disable Smarty rendering
$this->Front()->Plugins()->ViewRenderer()->setNoRender();
$this->Front()->Plugins()->Json()->setRenderer(false);
$orderModel = Shopware()->Models()->getRepository(Document::class)->findBy(['hash' =>$DocHarsh]);
$orderModel = Shopware()->Models()->toArray($orderModel);
$orderId = $orderModel[0]['documentId'];
$response = $this->Response();
$response->setHeader('Cache-Control', 'public');
$response->setHeader('Content-Description', 'File Transfer');
$response->setHeader('Content-disposition', 'attachment; filename=' . $orderId . '.pdf');
$response->setHeader('Content-Type', 'application/pdf');
$response->setHeader('Content-Transfer-Encoding', 'binary');
$response->setHeader('Content-Length', $filesystem->getSize($file));
$response->sendHeaders();
$response->sendResponse();
$upstream = $filesystem->readStream($file);
$downstream = fopen('php://output', 'wb');
while (!feof($upstream)) {
fwrite($downstream, fread($upstream, 4096));
}
error_log(print_r(array('leaving the pdf function',$DocHarsh,$orderId,$upstream,$downstream), true)."\n", 3, Shopware()->DocPath() . '/error.log');
}
Please have a look at backend-controller of the order module. It should be the same case. This function is used for opening/downloading a document from the backend:
https://github.com/shopware/shopware/blob/5.5/engine/Shopware/Controllers/Backend/Order.php#L1113
I think it might be confusing for backend users to be redirected (from the backend context) to a new blank page with a download.
According to my own evaluation. I think the issue you are having is because this is not an action but simply a function try making it an Action and run it through the browser like the original one.
Don't forget to whitelist it.
use the class use Shopware\Components\CSRFWhitelistAware;
then
something like this
/**
* {#inheritdoc}
*/
public function getWhitelistedCSRFActions()
{
return [
'youropenPdfActionnamewithoutthewordAction'
];
}
and also add the implements CSRFWhitelistAware to your class declaration.
I use the plugin 'blueimp jquery fileupload' to upload files in Javascript (that part I got it right) and then I have to handle the uploads on the server side using an uploadhandler affiliated to the plugin (UploadHandler.php).
Working in Symfony, I managed to create a service based on this php script and it works in my controller (the files are uploaded in the default repository, yet on my page I get the error message 'upload failed' and I don't know why but it's not a big problem I guess), but the thing is :
I would like to custom the repository path to upload the files based on the user id, and since I call the uploadhandler file as a service, I don't know how to override the options using the construct function, as I would be able to with a basic call in php.
Here's my code :
public function uploadFiles(Request $request)
{
$uploadhandler = $this->container->get('extranetcontratbundle.uploadhandler');
$response = $uploadhandler->response;
$files = $response['files'];
return new JsonResponse($files);
}
In the options of UploadHandler.php there is :
$this->options = array(
'script_url' => $this->get_full_url().'/'.$this->basename($this->get_server_var('SCRIPT_NAME')),
'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/files/',
'upload_url' => $this->get_full_url().'/files/',
'input_stream' => 'php://input',
'user_dirs' => false,
'mkdir_mode' => 0755,
'param_name' => 'files',
...blabla
And I would like to override the options in a similar way as I would in 'normal' php :
$tmpImagesDir = JPATH_ROOT . 'tmp' . $userId .;
$tmpUrl = 'tmp/' . $userId . '/' . '/';
$uploadOptions = array('upload_dir' => $tmpImagesDir, 'upload_url' => $tmpUrl);
$uploadHandler = new UploadHandler($uploadOptions);
But to do that I would have to write "require_once(blabla)" and I would have created the service for nothing. If I understood it right, that's not the way to do it in Symfony. Is there a way ?
Thank you for reading, please help.
I use the script php-soundcloud (Oauth 2) and want to change the title (Buy this track) of purchase link.
I can update the link but I can not change the text of link.
I use this code:
$soundcould->put('https://api.soundcloud.com/tracks/56649403', array(
'track[purchase_url]' => 'http://website.com/',
'track[purchase_title]' => 'Support me' // whitout this, it work
));
but it returns me an error: The requested URL responded with HTTP code 422.
When i remove track[purchase_title], it work, so the problem is that variable!
Must be something special to change the link title?
Soundcloud have posed limits on the use of their API?
It's possible to create a new link other than changing the variable purchase_title?
The reason this is not working is because the purchase_url and purchase_title can only be changed on premium accounts. I'll look at making this more clear in the docs!
Here's a code sample that will do the trick for a premium account:
<?php
require_once 'Services/Soundcloud.php';
$client = new Services_Soundcloud('client_id', 'client_secret', 'redirect_uri');
$client->setAccessToken('your-access-token');
$track_url = 'https://api.soundcloud.com/tracks/52652023.json';
$response = json_decode($client->put($track_url, array(
'track[purchase_url]' => 'http://website.com',
'track[purchase_title]' => 'Support me'
)));
?>
If that doesn't work, the problem is elsewhere. Email me and I can help you debug further.
I am not sure but try it. I think it is help full to you :-
See the guide:-
http://developers.soundcloud.com/docs/api/guide
Try it
<?php
$track = <<<EOH
<track>
<downloadable>true</downloadable>
<purchase_url>http://website.com/</purchase_url>
<purchase_title>true</purchase_title>
</track>
EOH;
try {
$response = json_decode(
$soundcloud->put(
'tracks/1',
$track,
array(CURLOPT_HTTPHEADER => array('Content-Type: application/xml'))
),
true
);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
I cannot understand how ->isuploaded() works. I am suppose to upload six images to display on my index page. Now the problem is, in my update function, if I upload only one or two image $upload->isUploaded() returns a false value, but if I decide to update all six of them it returns a true value. How do I deal with this problem? Am i missing out something here?
Here is my zend file transfer upload
$upload = new Zend_File_Transfer();
$upload->addValidator('Count', false, array('min' =>1, 'max' => 6))
->addValidator('Size', false, array('max' => '1Mb'))
->addValidator('ImageSize', false, array('minwidth' => 50,
'maxwidth' => 1000,
'minheight' => 50,
'maxheight' => 1000));
if ($upload->isUploaded()) $hasImage = true;
By default Zend guess all uploaded files are invalid even if just one of submitted form file fields was empty.
Zend docs are suggest to override this behavior by calling isValid() method before receive().
So I'm not sure if suggest best solution, but it works for me:
$upload = new Zend_File_Transfer();
$upload->setDestination( 'some your destination' );
if( $adapter->isValid( 'your form file field name' ) ){
$adapter->receive( 'your form file field name' );
}
And so on with every file field name. Wrap in foreach if needed.
Use isValid() instead.
if ($upload->isValid()) {
// success!
} else {
// failure!
}
Once you know your upload passed the validators, then start processing the images.