How to click button using Mechanize in perl? - html

<input type="hidden" name="hiddenConsolidateFiles" value="0">
<button type="button" style="width:220px;" onClick="javascript:viewFullTextOfTreaty()" value="full" name="full" id="full">View Full Text of Treaty</button>
<button type="button" style="display:none;" onClick="javascript:viewFullText()" value="" id="sim">View Other Relevant Treaty Information</button>
<button type="button" style="display:none;" onClick="javascript:viewConsolidated()" value="consol" name="consol" id="consol">View Consolidated Version of Treaty</button>
I have the above HTML. I want to click the button named full using Mechanize in perl. How can I do this?
I have tried $mech->click("full") and $mech->click_button(name => 'full') and $mech->click_button(value => 'full') but none have worked. They all say there is "no clickable input with name full".

I have no problems downloading your PDF:
my $url =
"http://ec.europa.eu/world/agreements/downloadFile.do?fullText=yes&treatyTransId=520";
{
my $mech = WWW::Mechanize->new();
$mech->get($url);
my ($filename) = $mech->{res}->{_headers}->{"content-disposition"} =~ m{filename=([^"]+)};
$mech->save_content($filename);
};
UPDATE
my $url =
"http://daccess-ods.un.org/access.nsf/Get?Open&DS=A/HRC/WGAD/2015/28&Lang=E";
my $mech = WWW::Mechanize->new();
$mech->get($url);
$mech->save_content("1.htm");
#HTTP-EQUIV="refresh" URL
my ($tmp_url) = $mech->content() =~ m{URL=([^"]+)};
$mech->get( "http://daccess-ods.un.org" . $tmp_url );
$mech->save_content("2.htm");
my ($pdf_url) = $mech->content() =~ m{URL=([^"]+)};
my ($cookie_url) = $mech->content() =~ m{src\s*=\s*"([^"]+)};
#First we need to get cookies
$mech->get($cookie_url);
#Next we can load PDF file
$mech->get($pdf_url);
$mech->save_content("Result.pdf");
Important note:
Parsing HTML with regular expressions is really bad idea (my favorite module is HTML::TreeBuilder::LibXML)

Related

Path file issue when uploading csv file via laravel form to database

I want to upload a csv file to my database via a laravel form. I can only insert file if the file is stored into public folder. How can I correctly set path with fopen function?
When submitting form, my code uses only the csv that already exists in public folder and not the csv I try to upload. Except from the csv I also pass some other data to my controller. How can I alter code to receive form file and not public folder stored file?
1) Below is my form excerpt. At the bottom lines I try to upload the file.
<body>
<form method='post' enctype="multipart/form-data" action="/hard">
{{csrf_field()}}
<section>
<br>
<legend><i><b> Complete Data Below</b></i></legend>
<br>
</section>
<section>
Choose program:
<select name="sc" id="xaos">
<optgroup label="postgraduates">
#foreach($transport as $y)
<option value="{{$y->object_id}}">{{$y->object_name}}</option>
#endforeach
</optgroup>
</select>
</section>
<br>
<section>
ID number:
<input name='am' type='number' min="1000000" max="1999999" required="" oninvalid="this.setCustomValidity('1000000 < Value < 1999999')">
</section>
<br>
<section>
Select Language:
<select name="language" id="lang">
<option value="GR"> Greek</option>
<option value="EN"> English</option>
</select>
</section>
<br>
<section>
<label for="upload-file">select csv file</label>
<input type="file" name="upload-file">
</div>
<input type='submit' name='upload' value="Submit!">
</section>
</form>
<br>
<br>
</body>
2) And below is my controller code excerpt which handles file imported.
public function job(Request $p)
{
$a1 = $p -> get('sc');
$a2 = $p -> get('am');
$a3 = $p -> get('language');
$f_rownum = 0;
if (($handle = fopen ( 'MOCK_DATA.csv', 'r' )) !== FALSE)
{
while ( ($data = fgetcsv ( $handle, 1000, ';' )) !== FALSE )
{
$ac1=$data[0];
$ac2=iconv("Windows-1253", "UTF-8", $data[1]);
$ac3=iconv("Windows-1253", "UTF-8", $data[2]);
$ac4=iconv("Windows-1253", "UTF-8", $data[3]);
$ac5=$data[4];
...............
According to Laravel documentation you can store your csv file into the storage like this:
public function storeFile(Request $request)
{
$path = $request->file('upload-file')->store('{directoryName}');
return $path;
}
The above code store your file in storage and returns tha path which you can save it into your DB.
For retrieving the file, you can use this code if you want to force user to download the file:
return Storage::download('{pathWhichYouSavedInDB}');
or you can retrieve the content of the file by using this code:
$contents = Storage::get('{pathWhichYouSavedInDB}');
[I add the extra response which I wrote in the comments]
fopen requires a full-path url of the stored file to be able to open it. So you can get the file url and then pass it to the fopen function like this:
$url = Storage::url('file.jpg');
Or you can not to use fopen at all and just use the $contents which you already retrieved with
$contents = Storage::get('{pathWhichYouSavedInDB}');

Upload and retrieve image in Laravel

I need to save the image for an avatar.
Can anyone give me a simple code to save and retrieve image?
I need to:
Save image in folder
Save image name in DB
Finally retrieve on image tag; I have to do it by Query Builder
Form:
<form action="" method="post" role="form" multiple>
{{csrf_field()}}
<legend>Form Title</legend>
<div class="form-group">
<label for="">Your Image</label>
<input type="file" name="avatar">
</div>
<button type="submit" class="btn btn-primary">save</button>
back
</form>
<img name="youravatar" src="">
</div>
Route:
Route::get('pic','avatarController#picshow');
Route::post('pic','avatarController#pic');
Controller:
I have the avatarController, but it is empty because I don't know what to do.
Database:
Table name: avatar
Fields: name id, imgsrc, created_at, Updated_at
Other:
I found this code but I can't find out anything:
if ($request->hasFile('avatar')) {
$file = array('avatar' => Input::file('avatar'));
$destinationPath = '/'; // upload path
$extension = Input::file('avatar')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension; // renaming image
Input::file('avatar')->move($destinationPath, $fileName);
}
First, make sure you have the encrypt attribute in your form
<form action="#" method="post" enctype="multipart/form-data">
You can use something similar to this in your controller
public function save(Request $request)
{
$file = $request->file('file');
// rename your file
$name = $file->getClientOriginalName();
\Storage::disk('local')->put($name, \File::get($file));
return "file saved";
}
Yes, you should store the file route in your database as well.
Make sure you are using a consistent path for your images like
Finally you have to create a route to give public access to your image file, like so:
Route::get('images/{file}', function ($file) {
$public_path = public_path();
$url = $public_path . '/storage/' . $file;
// file exists ?
if (Storage::exists($archivo))
{
return response()->file($pathToFile);
}
//not found ?
abort(404);
});
Check the docs about Laravel Responses
I hope this gives you an Idea of what to do.
Upload Image in laravel 5.4
check if request has image
$request->hasFile('image')
OR
$request->file('image')->isValid()
Now Save Image
$request->inputname->store('folder-name') return image path 'folder name/created image name
$request->image->store('images')
Check if image exits
Storage::disk('local')->exists('image name');
Delete Image
Storage::delete('image');
This is my code
if ($request->hasFile('image') && $request->file('image')->isValid())
{
$path = $request->image->store('images');
if(!empty($path)){
$edit = Model::FindOrFail($id);
// Delete old image
$exists = Storage::disk('local')->exists($edit->image);
if($exists){
Storage::delete($edit->image);
}
$edit->image = $path;
$edit->save();
}
}
Reference

Perl: Changing html element Label by ID

How does one with perl change an html element's value using the html element's ID. How do you do this in the code.
For example:
<div id="container">
<form id="form" action="../code.cgi" method="post">
<label id="lblMessage" class="text">Message</label>
</form>
</div>
How would I change the label's text in my perl script?
Get an HTML or XML parser find the element (e.g., by XPath expression), and remove all its child text nodes, and add a new text node with the text you want.
use strict;
use warnings;
use XML::LibXML;
my $dom = XML::LibXML->load_html(location => 'myfile.html');
my $xpath = XML::LibXML::XPathContext->new($dom);
foreach my $label ($xpath->findnodes('//label[#id="lblMessage"]')) {
$label->removeChildNodes();
$label->addChild($dom->createTextNode("new text"));
}
Caveat: if there are other nodes (elements, like <b> or <span>) in your label, these get removed as well.
You probably need to add some code to write the modified html back to a file.
I, personally like HTML::TreeBuilder for this sort of task.
use HTML::TreeBuilder;
my $html = <<END;
<div id="container">
<form id="form" action="../code.cgi" method="post">
<label id="lblMessage" class="text">Message</label>
</form>
</div>
END
my $root = HTML::TreeBuilder->new_from_content( $html );
$root->elementify(); # Become a tree of HTML::Element objects.
my $message = $root->find_by_attribute( 'id', 'lblMessage' )
or die "No such element";
$message->delete_content();
$message->push_content('I am new stuff');
print $root->as_HTML();

converting PDF to PNG with imagick and HTML input

I am trying to upload a Document (PDF) using HTML , and using imagick to convert it to a PNG if some one can look at my code and help me out I would greatly appreciate it, Thank You!!!
Also when I try to upload my document PDF thru I get a error message
Parse error: syntax error, unexpected '$image' (T_VARIABLE) in
C:\projects\magick2.php on line 27
Line 27 is associated with this code $image->setImageFormat('png')
<!DOCTYPE htlm>
<html>
<head>
<title>TEST!!!</title>
</head>
<div id = "cont">
<form method = "POST" enctype = "multipart/form-data" action = "magick2.php">
<div id = "choose">
File:
<input type="file" name="image" size = "40" id = "fimage" accept = "application/pdf">
<input type="submit" value="UpLoad" name = "wang">
</div>
</form>
</div>
<?php
$image = new Imagick();
$image->readImage(string ($_POST['wang'])
$image->setImageFormat('png');
$image->writeImage('C:\projects\matt.png');
$img = $image;
echo "<img src = matt.png >";
$img->clear();
$img->destroy();
?>
</html>
I am not going in to much details, but the actual reason for that error message is 'missing semi colon on the line above it'.
$image->readImage(string ($_POST['wang'])
you should receive "image" instead of "wang"
$image->readImage(string ($_POST['image'])

Accessing data from Wikidata JSON file

I'm trying to access the following properties from the Wikidata API: id, url, aliases, description and label but so far have been unsuccessful. I'm sure I'm making basic mistakes and so far only have the following code. Any suggestions as to the best way to access this data is much appreciated.
<html>
<body>
<form method="post">
Search: <input type="text" name="q" value="Google"/>
<input type="submit" value="Submit">
</form>
<?php
if (isset($_POST['q'])) {
$search = $_POST['q'];
$errors = libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile("https://www.wikidata.org/w/api.php?
action=wbsearchentities&search=Google&format=json&language=en");
libxml_clear_errors();
libxml_use_internal_errors($errors);
}
?>
</body>
</html>
Edit - I have managed to get a string ($jsonArr) containing particular data that I would like. However I would like to get the first instance of the particular elements from the string specifically id, url, alias, description and label i.e. specifically: variable1 - Q95, variable2 - //www.wikidata.org/wiki/Q95, variable3 - Google.Inc, varialbe4 - American multinational Internet and technology corporation, variable5 - Google/ Please see code below:
<HTML>
<body>
<form method="post">
Search: <input type="text" name="q" value="Google"/>
<input type="submit" value="Submit">
</form>
<?php
if (isset($_POST['q'])) {
$search = $_POST['q'];
$errors = libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile("https://www.wikidata.org/w/api.php?
action=wbsearchentities&search=$search&format=json&language=en");
libxml_clear_errors();
libxml_use_internal_errors($errors);
var_dump($doc);
echo "<p>";
$jsonArr = $doc->documentElement->nodeValue;
$jsonArr = (string)$jsonArr;
echo $jsonArr;
}
?>
</body>
</HTML>
You need to show the JSON you want to parse...
Basicly you can get values out of JSON in PHP like this...
If $doc is the JSON you want to parse
$jsonArr = json_decode($doc, true);
$myValue = $jsonArr["keyYouWant"];
Edit after understanding what you are doing there :-)
Hi, Im sorry I was completely confused of what you were doing there... So I have testet your code on my server and just get what you want...
Following the code you wanted... I took clear var names, so they are a little bit longer, but easier to understand...
$searchString = urlencode($_POST['q']); //Encode your Searchstring for url
$resultJSONString = file_get_contents("https://www.wikidata.org/w/api.php?action=wbsearchentities&search=".$searchString."&format=json&language=en"); //Get your Data from wiki
$resultArrayWithHeader = json_decode($resultJSONString, true); //Make an associative Array from respondet JSON
$resultArrayClean = $resultArrayWithHeader["search"]; //Get the search Array and ignore the header part
for ($i = 0; $i < count($resultArrayClean); $i++) { //Loop through the search results
echo("<b>Entry: ".$i."</b>");
echo("<br>");
echo($resultArrayClean[$i]["id"]); //Search results value of key 'id' at position n
echo("<br>");
echo($resultArrayClean[$i]["url"]); //Search results value of key 'url' at position n
echo("<br>");
echo($resultArrayClean[$i]["aliases"]); //Search results value of key 'aliases' at position n
echo("<br>");
echo("<br>");
echo("<br>");
}