perl CGI radio button form - forms

I have following CGI snippet from my code. its create textarea to type my message which i want to send, but i want to convert that into template style like "radio", so i select just radio button and it will inject whatever message into notification for customer, so i don't need to type message every time. just like template. Anybody has any example or code which can fix in my requirement?
use CGI;
use CGI::Carp;
...
...
$html .= $q->b("Customer Notification:") . $q->br;
$html .= $q->textarea(-name=>'notification',
-rows=>4,
-columns=>60) . $q->p;
$html .= $q->submit(-name=>' Send Notification ');
$html .= " ";
$html .= $q->reset(-name=>' Reset to Original Value ');
$html .= $q->p;

Like others have mentioned, you should really consider using one of the other solutions found in CGI::Alternatives.
Nevertheless...
my %labels = (
'comment' => 'General Comment',
'problem' => 'Non-critical Problem',
'emergency' => 'Critical Emergency',
);
$html .= $q->radio_group(
-name=>'notification',
-values=>['comment','problem','emergency'],
-default=>'comment',
-linebreak=>'true',
-labels=>\%labels,
);

Related

Sending a mail with a dynamic table from perl script

I have the following code in Perl:
foreach my $result ( #results ) {
if ( $result->{Error} ) {
print"No response received \n";}
else {
my $H = "$result->{H}";
my $I = "$result->{I}";
$mailbody.=qq(<h4 style="background: blue; color: white;">$H--->$I</h4>);
}
}
Here, I am using Mime::Lite to send mails:
$msg = MIME::Lite->new(
From => $from,
To => $to,
Cc => $cc,
Subject => $subject,
Data => $mailbody
);
$msg->attr("content-type" => "text/html/css");
$msg->send;
What I want is that the result data i.e $H and $I to be represented in the form of a table in the mail.
H | I
1 | 46
2 | 565756756767
3 | 232132
The number of rows of the table are dynamic and depend on the input given by the user. How can I do this?
If you want it to be a table in the email, you should create a table in the email body something like this:
$mailbody . = '<table>';
foreach my $result ( #results ) {
if ( $result->{Error} ) {
print"No response received \n";}
else {
my $H = "$result->{H}";
my $I = "$result->{I}";
$mailbody.=qq(<tr><td>$H</td><td>$I</td></tr>);
}
}
$mailbody . = '</table>';
If you want an HTML table in your email, then add HTML table elements to your output.
# Note: border=1 attribute to make the table borders visible.
$mailbody .= '<table border="1">';
foreach my $result ( #results ) {
if ( $result->{Error} ) {
print"No response received \n";}
else {
$mailbody .= qq(<tr><td>$result->{H}</td>)
. qq(<td>$result->{I}</td></tr>);
}
}
$mailbody .= </table>
In a comment to another answer that suggested something similar, you said that this doesn't work because you can't see the table borders. That was, of course, a simple case of adding border=1 so that the borders are displayed.
However.
It's always worth repeating that putting raw HTML strings into your program code is a terrible idea. It's a recipe for an unmaintainable mess. It's a bad idea when creating web applications and it's a bad idea when creating HTML to go into email bodies.
Far better to separate the code from creating the output and the best way to do that is to use a templating engine like the Template Toolkit. By creating a template file that contains all of the HTML output, you make it easier to change the way that the HTML looks without getting bogged down in the Perl code.
Also (and I've suggested this to you before) I would suggest that you avoid using MIME::Lite. But don't take my word for it. The current documentation for the module says this:
MIME::Lite is not recommended by its current maintainer. There are a number of alternatives, like Email::MIME or MIME::Entity and Email::Sender, which you should probably use instead. MIME::Lite continues to accrue weird bug reports, and it is not receiving a large amount of refactoring due to the availability of better alternatives. Please consider using something else.
I recommend switching to Email::Sender (together with Email::MIME) or Email::Stuffer.

Two contact forms, send to two different email addresses

I got two contact forms on my website. On in the contact section, and one in the careers section. I want to receive both forms in different email adresses.
<?php
include_once('class.phpmailer.php');
$mail = new PHPMailer;
$mail->setFrom('adres1','test');
$mail->Subject = 'Contactverzoek via careerspagina.';
$html = "Er is een contactverzoek gedaan via de careerspagina.<br>";
$html .= "<br>";
$html .= "<b>Naam:</b> " . $_POST['name']."<br>";
if(isset($_POST['lastname'])) {
$html .= '<b>Achternaam: </b> ' . $_POST['lastname']."<br>";
}
$html .= "<b>E-mail:</b> " . $_POST['email']."<br>";
if(isset($_POST['telefoon'])) {
$html .= '<b>Telefoon: </b> ' . $_POST['telefoon']."<br>";
}
if(isset($_POST['onderwerp'])) { //FIX NOG!!!
$html .= '<b>Onderwerp: </b> ' . $_POST['onderwerp']."<br>";
}
if(isset($_POST['Werkervaring'])) {
$html .= '<b>Werkervaring: </b> ' . $_POST['Werkervaring']."<br>";
}
if(isset($_POST['Functie'])) {
$html .= '<b>Functie: </b> ' . $_POST['Functie']."<br>";
}
if(isset($_POST['Opleidingsniveaus'])) {
$html .= '<b>Opleidingsniveaus: </b> ' . $_POST['Opleidingsniveaus']."<br>";
}
if(isset($_POST['comment'])) {
$html .= '<b>Bericht: </b> ' . $_POST['comment']."<br>";
}
$html .= "<br>";
if (isset($_FILES['resume']) &&
$_FILES['resume']['error'] == UPLOAD_ERR_OK) {
$mail->AddAttachment($_FILES['resume']['tmp_name'],
$_FILES['resume']['name']);
}
if (isset($_FILES['letter']) &&
$_FILES['letter']['error'] == UPLOAD_ERR_OK) {
$mail->AddAttachment($_FILES['letter']['tmp_name'],
$_FILES['letter']['name']);
}
$mail->msgHTML($html);
$mail->addAddress('adres1', 'Info ');
$mail->addBCC('adres1', 'Test ');
if(!$mail->send())
{
echo "0";
}
else
{
echo "1";
}
This is my code, and everything seems to work.
So once again. I want to keep sending this contact form to email A. But There needs to be made and else statement which sends the other contact form to email B.
i'm very new to PHP. Excuse me if i'm not clear.
One simple solution is to send a form parameter indicating which email address should be used. Then you check the POST variable for that parameter in an if statement and set the correct email address to be used.
$to = "forma#example.com";
if($_POST['form'] === "formB") {
$to = "formb#example.com";
}
$mail->addAddress($to, 'Recipient name');
Add hidden inputs in your forms named "form" and set the value to either "formA" or "formB":
<input type="hidden" name="form" value="formA">
Do not set the receiving email address in the form and use that since it can easily be abused to send spam from your server.

replace text with url in twitter feed

I have this code:
public function linkify($status_text)
{
$status_text = preg_replace('/(https?:\/\/\S+)/','\1', $status_text);
$status_text = preg_replace('/(^|\s)#(\w+)/','\1#\2',$status_text);
$status_text = preg_replace('/(^|\s)#(\w+)/','\1#\2',$status_text);
return $status_text;
}
and display feeds from twitter like this
foreach($feed as $feed_item) {
$html .= '<li>';
$html .= '' . $this->linkify($feed_item->text) . '';
$html .= '' . $this->relativedate((strtotime($feed_item->created_at))) . '';
$html .= '</li>';
}
echo $html;
result of this code is
<li>Twitter Feed Text http://t.co/TnkNfxCdRu</li>
if anyone can help me, how can I add text inside tag <a></a>. for example, to be exactly like this:
<li>Twitter Feed Text</li>
Thank you so much
Just change your first preg_replace to:
$status_text = preg_replace('~(https?://(\S+))~','$2',$status_text);

Zend Framework 2 form element error-class + custom ViewHelper to render form

This is my third question this week (and overall) - hope I don't get banned here :D
Anyway, searched around and couldn't find an exact explanation to solve my issue(s).
A. I've searched around and found a custom ViewHelper to render my forms. What it does is recursively get all fieldsets and when it gets to the element level, it goes like this:
public function renderElement($element) {
$html = '
<div class="row">' .
'<label class="col-md-12" for="' . $element->getAttribute('id') . '">' . $element->getLabel() . '</label>' .
$this->view->formElement($element) .
$this->view->FormElementErrors($element) .
'<div class="clearfix" style="height: 15px;"></div>';
return $html . PHP_EOL;
}
Form renders ok, except:
1) How can I add an error class to the form element? (like if I use formRow helper in my view, it automatically ads an 'input-error' class, while also keeping the initial class specified in my fieldset when creating the element - 'attributes' => array('class' => 'some-class')), so the element's class attribute becomes "some-class input-error" in case it's invalid.
2) How can I set a class for the 'ul' containing the error messages (the 'ul' rendered by $this->view->FormElementErrors($element))? Hope this is a one-liner and I don't have to go message-by-message and compose the html for the error messages list, but if not so be it (I don't know how to do that either).
B. Let's say that sometimes I don't use this custom ViewHelper to render my form. Zend's formRow view helper can be handy sometimes. This brings me to the following code in my view:
echo $this->formRow($this->form->get('user_fieldset')->get('user_name'));
I've noticed this automatically adds 'input-error' class on my element (in case it's invalid) which is perfect, BUT how can I also tell formRow to give a class to the 'ul' that's displaying the error messages?
I'd go even further and ask how I can turn this:
echo $this->formLabel($this->form->get('user_fieldset')->get('user_name'));
echo $this->formInput($this->form->get('user_fieldset')->get('user_name'));
echo $this->formElementErrors($this->form->get('user_fieldset')->get('user_name'), array('class' => 'form-validation-error'));
into something that ads an error-class to the element as well, not just to the error messages list, but if anyone answers to point A I think it's the same issue.
I've managed to do it like this:
public function renderElement($element) {
// FORM ROW
$html = '<div class="form-group">';
// LABEL
$html .= '<label class="form-label" for="' . $element->getAttribute('id') . '">' . $element->getLabel() . '</label>';
// ELEMENT
/*
- Check if element has error messages
- If it does, add my error-class to the element's existing one(s),
to style the element differently on error
*/
if (count($element->getMessages()) > 0) {
$classAttribute = ($element->hasAttribute('class') ? $element->getAttribute('class') . ' ' : '');
$classAttribute .= 'input-error';
/*
* Normally, here I would have added a space in my string (' input-error')
* Logically, I would figure that if the element already has a class "cls"
* and I would do $element->getAttribute('class') . 'another-class'
* then the class attribute would become "clsanother-class"
* BUT it seems that, even if I don't intentionally add a space in my string,
* I still get "cls another-class" as the resulted concatenated string
* I assume that when building the form, ZF2 automatically
* adds spaces after attributes values? so you/it won't have to
* consider that later, when you'd eventually need to add another
* value to an attribute?
*/
$element->setAttribute('class', $classAttribute);
}
$html .= $this->view->formElement($element);
/*
* Of course, you could decide/need to do things differently,
* depending on the element's type
switch ($element->getAttribute('type')) {
case 'text':
case 'email': {
break;
}
default: {
}
}
*/
// ERROR MESSAGES
// Custom class (.form-validation-error) for the default html wrapper - <ul>
$html .= $this->view->FormElementErrors($element, array('class' => 'form-validation-error'));
$html .= '</div>'; # /.form-group
$html .= '<div class="clearfix" style="height: 15px;"></div>';
return $html . PHP_EOL;
}
I'm not to fond of this, but I suppose there is no shorter way. I thought ZF2 shoud have something like:
if ($element->hasErrors()) { $element->addClass('some-class'); }
right out of the box. That's the answer I would have expected, that it would simply be a method I missed/couldn't find. But it turns out that ZF2 doesn't have quite anything in the whole world that you might need right out of the box, you end up having to write the (more or less) occasional helpers.
Anyway, if someone ever needs it here's the entire RenderForm view helper:
namespace User\View\Helper;
use Zend\View\Helper\AbstractHelper;
class RenderForm extends AbstractHelper {
public function __invoke($form) {
$form->prepare();
$html = $this->view->form()->openTag($form) . PHP_EOL;
$html .= $this->renderFieldsets($form->getFieldsets());
$html .= $this->renderElements($form->getElements());
$html .= $this->view->form()->closeTag($form) . PHP_EOL;
return $html;
}
public function renderFieldsets($fieldsets) {
foreach ($fieldsets as $fieldset) {
if (count($fieldset->getFieldsets()) > 0) {
$html = $this->renderFieldsets($fieldset->getFieldsets());
} else {
$html = '<fieldset>';
// You can use fieldset's name for the legend (if that's not inappropriate)
$html .= '<legend>' . ucfirst($fieldset->getName()) . '</legend>';
// or it's label (if you had set one)
// $html .= '<legend>' . ucfirst($fieldset->getLabel()) . '</legend>';
$html .= $this->renderElements($fieldset->getElements());
$html .= '</fieldset>';
// I actually never use the <fieldset> html tag.
// Feel free to use anything you like, if you do have to
// make grouping certain elements stand out to the user
}
}
return $html;
}
public function renderElements($elements) {
$html = '';
foreach ($elements as $element) {
$html .= $this->renderElement($element);
}
return $html;
}
public function renderElement($element) {
// FORM ROW
$html = '<div class="form-group">';
// LABEL
$html .= '<label class="form-label" for="' . $element->getAttribute('id') . '">' . $element->getLabel() . '</label>'; # add translation here
// ELEMENT
/*
- Check if element has error messages
- If it does, add my error-class to the element's existing one(s),
to style the element differently on error
*/
if (count($element->getMessages()) > 0) {
$classAttribute = ($element->hasAttribute('class') ? $element->getAttribute('class') . ' ' : '');
$classAttribute .= 'input-error';
$element->setAttribute('class', $classAttribute);
}
$html .= $this->view->formElement($element);
// ERROR MESSAGES
$html .= $this->view->FormElementErrors($element, array('class' => 'form-validation-error'));
$html .= '</div>'; # /.row
$html .= '<div class="clearfix" style="height: 15px;"></div>';
return $html . PHP_EOL;
}
}
User is my module. I've created a 'viewhelper.config.php' in it's config folder:
return array(
'invokables' => array(
'renderForm' => 'User\View\Helper\RenderForm',
),
);
and in Module.php:
public function getViewHelperConfig() {
return include __DIR__ . '/config/viewhelper.config.php';
}
Then, in your view simply call:
$this->renderForm($form);
Of course, if you don't have many view helpers, you could not create a separate config file just for that, leave Module.php alone and simply add:
'view_helpers' => array(
'invokables' => array(
'renderForm' => 'User\View\Helper\RenderForm',
),
),
to any configuration file.
I use getMessages() method to check if an element has an validation message. for eg.
<div class="form-group <?=($this->form->get('user_fieldset')->get('user_name')->getMessages())?'has-error':'';?>">
...
</div>
This question seems to be very old and you must have solved it by yourself. :)

Email::MIME can't parse message from Gmail

So I'm using PERL and Email::MIME to get an email from gmail. Here is my code:
use Net::IMAP::Simple::Gmail;
use Email::Mime;
# Creat the object that will read the emails
$server = 'imap.gmail.com';
$imap = Net::IMAP::Simple::Gmail->new($server);
# User and password
$user = 'username#gmail.com';
$password = 'passowrd';
$imap->login($user => $password);
# Select the INBOX and returns the number of messages
$numberOfMessages = $imap->select('INBOX');
# Now let's go through the messages from the top
for ($i = 1; $i <= $numberOfMessages; $i++)
{
$top = $imap->top($i);
print "top = $top\n";
$email = Email::MIME->new( join '', #{ $imap->top($i) } );
$body = $email->body_str;
print "Body = $body\n";
}#end for i
When I run it, I get the following error:
can't get body as a string for multipart/related; boundary="----=_Part_6796768_17893472.1369009276778"; type="text/html" at /Library/Perl/5.8.8/Email/Mime.pm line 341
Email::MIME::body_str('Email::MIME=HASH(0x87afb4)') called at readPhoneEmailFeed.pl line 37
If I replace
$body = $email->body_str;
with
$body = $email->body;
I get the output:
Body =
(i.e. empty string)
What's going on here? is there a way for me to get the raw body of the message (->body_raw doesn't work either)? I'm okay with parsing out the body using regex
Email::MIME is not the best documented package I have ever seen.
The body and body_str methods only work on a single mime part. Mostly that would be a simple text message. For anything more complex use the parts method to get each mime component which is itself an Email::MIME object. The body and body_str methods should work on that. An html formatted message will generally have two MIME parts: text/plain and text/html.
This isn't exactly what you want but should be enough to show you what is going on.
my #parts = $email->parts;
for my $part (#parts) {
print "type: ", $part->content_type, "\n";
print "body: ", $part->body, "\n";
}