Incorrect password encryption - symfony

I have a small password encryption problem ^^
in my database the passwords are present, and have to present, in this form:
VwBybV5ATQ9RkdvvVZNOlldEEDU9tDjttju7t8l+HeVe4nskHeMpbuCoQsqqORUQKZ1pg7gGtFocpkSIw8N9kA==
and right now I have a function that needs to generate a password for me. Unfortunately the encryption is not good, because that's what I get:
YmY1NzFkM2VkODYwOGQ1OWFlMTRiZDVkOTc3ZDFkNzQ0ODIzN2U5NWMzNzU0ZjI1Y2U4MTZhYzBiYmExYWJjZTg2Y2JjNzYyM2QwYTJmMDUwYWJiMzQxMjliYjBjYWQxMGZiMzliYzk3OGQwZjYxMGU3Y2E0NjE0ZTkxYzFiYmM=
my code :
public function lostpasswordAction(Request $request)
{
$success = '';
$string = '';
$characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
$max = strlen($characters) - 1;
for ($i = 0; $i < 12; $i++) {
$string .= $characters[mt_rand(0, $max)];
}
if ($request->request->get('email') !== null) {
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('ApplicationSonataUserBundle:User')->findByEmail($request->request->get('email'));
if (is_null($user)) {
$response = new JsonResponse('Not Found');
$response->setStatusCode(Response::HTTP_NOT_FOUND);
return $response;
}
$login = $user[0]->getEmail();
$password = $string;
$user[0]->setPassword(hash('sha512',$password));
$em->persist($user[0]);
$em->flush();
$message = \Swift_Message::newInstance()
->setSubject('Subject')
->setFrom('no-reply#noreply.com')
->setTo($request->request->get('email'))
->setBody(
$this->renderView(
'emails/lostpassword.txt.twig',
array(
'login' => $login,
'password' => $password
)
),
'text/plain'
);
$return = $this->get('mailer')->send($message);
$success = 'Email sent';
return new JsonResponse($success);
}
$response = new JsonResponse('POST only');
$response->setStatusCode(Response::HTTP_BAD_REQUEST);
return $response;
}
Can someone help me so I get the right shape please?
Thank you in advance

Related

Drupal 7: How to send HTML Email

Could someone tell me what i am missing to send an HTML email using Drupal's function? Here is my call:
try{
drupal_mail('my_module', 'forgot', $node->field_email_address['und'][0]['value'], language_default(), array('reset_key' => $key),'do-not-reply#myemailaddress.com');
}catch(Exception $e){
print_r($e->getMessage());die();
}
And here is the function:
function my_module_mail($key, &$message, $params) {
$body = '<p>Click the link below to reset your password.</p>
<p>Click this link to reset your password</p>
';
// $headers = array(
// 'MIME-Version' => '1.0',
// 'Content-Type' => 'text/html; charset=UTF-8; format=flowed',
// 'Content-Transfer-Encoding' => '8Bit',
// 'X-Mailer' => 'Drupal'
// );
// $message['headers'] = $headers;
$message['subject'] = 'Why wont this send html??';
$message['headers']['Content-Type'] = 'text/html; charset=UTF-8;';
$message['body'][] = $body;
$message['from'] = 'do-not-reply#myemailaddress.com';
}
I tired just the html header and the full set that is commented out. What am I missing? The email sends fine but it's plain text. Thanks and let me know!
You can use this function
function my_module_custom_drupal_mail($target = NULL, $from = null, $subject, $message, $attachment = NULL){
$my_module = 'my_module';
$my_mail_token = microtime();
$message = array(
'id' => $my_module . '_' . $my_mail_token,
'to' => $target,
'subject' => $subject,
'body' => array($message),
'module' => $my_module,
'key' => $my_mail_token,
'from' => "$from <email#email.com>",
'headers' => array(
'From' => "$from <email#email.com>",
'Sender' => "$from <email#email.com>",
'Return-Path' => "$from <email#email.com>",
'Content-Type' => 'text/html; charset=utf-8'
),
);
if ($attachment) {
$file_content = file_get_contents($attachment[0]);
$message['params']['attachments'][] = array(
'filecontent' => $file_content,
'filename' => $attachment[1],
'filemime' => $attachment[2],
);
}
$system = drupal_mail_system($my_module, $my_mail_token);
$message = $system->format($message);
if ($system->mail($message)) {
return TRUE;
}
else {
return FALSE;
}
}
AND call it like :
$body = '<p>Click the link below to reset your password.</p>
<p>Click this link to reset your password</p>
';
$subject ='Why wont this send html??';
$from = 'myemail#email.com';
$sent = my_module_custom_drupal_mail($node->field_email_address['und'][0]['value'], $from, $subject, $body);
Customize it like you want ! :)
A few things need to be done:
/**
* Class SomeCustomModuleMailSystem Implements MailSystemInterface.
*
* Used to enable HTML email to be sent.
*/
class SomeCustomModuleMailSystem extends DefaultMailSystem {
public function format(array $message) {
$message['body'] = implode("\n\n", $message['body']);
$message['body'] = drupal_wrap_mail($message['body']);
return $message;
}
}
This to be done one time, so probably in a hook_enable or hook_update:
$current = variable_get('mail_system', ['default-system' => 'DefaultMailSystem']);
$addition = ['some_custom_module' => 'SomeCustomModuleMailSystem'];
variable_set('mail_system', array_merge($current, $addition));
Invoke hook_mail as normal, e.g.
/**
* Implements hook_mail().
*/
function some_custom_module_mail($key, &$message, $params) {
switch ($key) {
case 'some_mail_key':
$message['headers']['Content-Type'] = 'text/html; charset=UTF-8;';
$message['subject'] = $params['subject'];
$message['body'][] = $params['body'];
break;
}
}
Finally call it with something like this:
// Set variables required for the email.
$module = 'some_custom_module';
$key = 'some_mail_key';
$to = $email = 'thetoaddress#something.com';
$language = language_default();
$params['subject'] = 'Email subject';
$params['body'] = '<html><body>The HTML!</body></html>';
$from = 'thefromaddress#something.com';
$send = TRUE;
// Send the mail and log the result.
$result = drupal_mail($module, $key, $to, $language, $params, $from, $send);
if ($result['result'] === TRUE) {
watchdog('some_custom_module', 'HTML email successfully sent.', [], WATCHDOG_INFO);
}
else {
watchdog('some_custom_module', 'HTML email failed to send', [], WATCHDOG_ERROR);
}

How avoid form resubmission on page refresh?

I'm doing a simple feedback form on WordPress. And like many people, I encountered the problem of resending the form when refresh the browser page. I know that this problem is solved through the use of the pattern "Post/Redirect/Get". Which says that you need after processing the data $_POST, request the same page using the $_GET method. But I can not use the result of the wp_mail function for redirection.
if(wp_mail($email, $email_subject, $email_message, $headers)) {
add_action('send_headers', 'simplemail_add_header');
}
function simplemail_add_header() {
header("Location: http://google.com");
}
It just does not work.
UPD
Here is my full code:
class SimpleMailer {
private $nonce = 'feedback_nonce';
public function __construct() {
add_action('phpmailer_init', array($this, 'simplemail_smtp_config'));
add_shortcode('simplemail', array($this, 'simplemail_sendmail'));
}
public function simplemail_smtp_config($phpmailer) {
$phpmailer->isSMTP();
$phpmailer->SetFrom("admin#mail.com");
$phpmailer->addAddress("sender#mail.com");
$phpmailer->Host = "ssl://smtp.mail.com";
$phpmailer->SMTPAuth = true;
$phpmailer->Port = 465;
$phpmailer->Username = "admin#mail.com";
$phpmailer->Password = "password";
$phpmailer->SMTPSecure = 'ssl';
}
public function simplemail_sendmail($shortcode_attributes) {
global $wp;
$result = "";
$error = false;
$data = array();
$required_fields = array("feedback_name", "feedback_email", "feedback_message");
$atts = shortcode_atts(array(
"email" => get_bloginfo('admin_email'),
"form_action" => home_url($wp->request),
"form_cls" => '',
"mail_subject" => "Feedback message from",
"pls_name" => 'Your Name',
"pls_email" => 'Your E-mail Address',
"pls_message" => 'Your Message',
"label_submit" => 'Submit',
"error_common" => 'There was some mistake. Try again, a little later.',
"error_empty" => 'Please fill in all the required fields.',
"error_noemail" => 'Please enter a valid e-mail address.',
"success" => 'Thanks for your e-mail! We\'ll get back to you as soon as we can.'
), $shortcode_attributes);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
foreach ($_POST as $field => $value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$data[$field] = trim(strip_tags($value));
}
foreach ($required_fields as $required_field) {
$value = trim($data[$required_field]);
if(empty($value)) {
$error = true;
$result = $atts['error_empty'];
}
}
if(!empty($data["feedback_blank"])) {
$error = true;
$result = $atts['error_empty'];
}
if(!is_email($data['feedback_email'])) {
$error = true;
$result = $atts['error_noemail'];
}
if(!wp_verify_nonce($data[$this->nonce],'simplemail_nonce')) {
$error = true;
$result = $atts['error_common'];
}
if ($error == false) {
$email_subject = $atts['mail_subject']." [".get_bloginfo('name')."]";
$email_message = $data['feedback_message']."\n\n";
$headers = "From: ".$data['feedback_name']." <".$data['feedback_email'].">\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
if(wp_mail(null, $email_subject, $email_message, $headers)) {
add_action('send_headers', array($this, 'simplemail_add_header', 10, $atts['form_action']));
// wp_redirect( 'http://google.com', 301 );
// exit;
}
$data = array();
$result = $atts['success'];
}
}
return $this->simplemail_draw_form($atts, $data, $result);
}
public function simplemail_draw_form($atts, $data, $result) {
$output = "<form action='".$atts['form_action']."' class='".$atts['form_cls']."' method='post'>".PHP_EOL.
"<input type='text' name='feedback_name' placeholder='".$atts['pls_name']."' value='".#$data['feedback_name']."'>".PHP_EOL.
"<input type='text' name='feedback_blank'>".PHP_EOL.
"<input type='email' name='feedback_email' placeholder='".$atts['pls_email']."' value='".#$data['feedback_email']."'>".PHP_EOL.
"<textarea name='feedback_message' cols='30' rows='10' placeholder='".$atts['pls_message']."'>".#$data['feedback_message']."</textarea>".PHP_EOL;
$output .= wp_nonce_field('simplemail_nonce', $this->nonce, false);
$output .= ($result != "") ? '<div class="feedback-info">'.$result.'</div>' : '<div class="feedback-info"></div>';
$output .= "<button type='submit'>".$atts['label_submit']."</button>".PHP_EOL."</form>";
return $output;
}
public function simplemail_add_header($location) {
header("Location: {$location}");
}
}
$simplemailer = new SimpleMailer();
And I get this error if I uncomment the redirect. And nothing at all, if you try to use simplemail_add_header
Warning: Cannot modify header information - headers already sent by (output started at /var/www/vhosts/12/151953/webspace/httpdocs/skgk.kz/wp-includes/nav-menu-template.php:256) in /var/www/vhosts/12/151953/webspace/httpdocs/skgk.kz/wp-includes/pluggable.php on line 1216
I think you need to add a token in a hidden textbox and within the form to be submitted, the text in this text box will be the token and it need to change on every page load. Save this token in a session variable. Then add a condition at the top of the page to validate the token, if the token is different kill the loading process or display a message or whatever you feel is needed. You may also add token longevity to allow submitting of a page within certain amount of time.
The token creation, token validation and token longevity are normally a function somewhere that is called as needed and form different pages.
Edit:
If all you want is redirect the user to a different page then do:
if(mail succeed) {
header('location: thankyou.html');
}

why csv export not working?

I try to do a csv export on my symfony project and i think that something is wrong because the function return a simple response and don't download the csv.
here is the function:
public function exportCsv($customers)
{
$fileName = "export_" . date("d_m_Y") . ".csv";
$response = new StreamedResponse();
$handle = fopen('php://output', 'w+');
fputcsv($handle, array('Name',
'Adress',
'City',
'Code'
), ';');
foreach ($customers as $index => $custom)
{
fputcsv($handle,array(
$custom->getName(),
$custom->getAdress(),
$custom->getCity(),
$client->getCode(),
),';');
}
fclose($handle);
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
$response->headers->set('Content-Disposition','attachment; filename='.$fileName);
return $response;
}
After creating a streamed response object, you needed to add the callback function that will fill out your response object with content: $response->setCallback().
public function exportCsv($customers)
{
$fileName = "export_" . date("d_m_Y") . ".csv";
$response = new StreamedResponse();
$response->setCallback(function() {
$handle = fopen('php://output', 'w+');
fputcsv($handle, array('Name', 'Adress', 'City', 'Code'),';');
foreach ($customers as $index => $custom)
{
fputcsv($handle,array(
$custom->getName(),
$custom->getAdress(),
$custom->getCity(),
$client->getCode(),
),';');
}
fclose($handle);
});
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
$response->headers->set('Content-Disposition','attachment;
filename='.$fileName);
return $response;
}

Functional Testing in Symfony

I am new in testing.I want to test my function.I have successfully installed phpUnit. I check many tutorials on internet.But I could not get the proper information regarding testing. Here is the my function code:
public function loginAction(Request $request)
{
$session = $this->getRequest()->getSession();
if( $session->get('userId') && $session->get('userId') != '' && $session->get('type') == '2')
{
//if user is login then it will be redirect to login page
return $this->redirect($this->generateUrl('registrarGeneral_dashboard'));
}
$em = $this->getDoctrine()->getEntityManager();
$repository = $em->getRepository('DRPAdminBundle:User');
if ($request->getMethod() == 'POST')
{
$session->clear();
$userName = $request->get('username');
$password = md5($request->get('password'));
//find email, password type and status of User
$user = $repository->findOneBy(array('username' => $userName, 'password' => $password,'type'=>2,'status'=>1 ));
$userEmail = $repository->findOneBy(array('email' => $userName, 'password' => $password,'type'=>2,'status'=>1 ));
if ($user)
{
//set session of User login
$session->set('userId', $user->getId());
$session->set('type', 2);
$session->set('nameRegistrar', $user->getFirstName());
$session->set('pictureRegistrar', $user->getPicture());
//echo "<pre>";print_r($session->get('picture'));die;
return $this->redirect($this->generateUrl('registrarGeneral_dashboard'));
}
if ($userEmail)
{
$session->set('type', 2);
$session->set('userId', $userEmail->getId());
$session->set('nameRegistrar', $userEmail->getFirstName());
$session->set('pictureRegistrar', $userEmail->getPicture());
//echo "<pre>";print_r($session->get('picture'));die;
return $this->redirect($this->generateUrl('registrarGeneral_dashboard'));
}
else
{
return $this->render('DRPRegistrarGeneralBundle:Pages:login.html.twig', array('name' => 'Invalid Email/Password'));
}
}
return $this->render('DRPRegistrarGeneralBundle:Pages:login.html.twig');
}
how to test this function? Please help
I don't know what you want to test but here is an exemple of what you can do to test user fonctionnalities :
public function testUserPageDown()
{
$client = static::createClient();
$client->request('GET', '/user/login');
$this->assertTrue($client->getResponse()->isSuccessful());
$client->request('GET', '/user/register');
$this->assertTrue($client->getResponse()->isSuccessful());
}
public function testUserFirewall()
{
$client = static::createClient();
//Trying go to user routes without being logged
$client->request('GET', '/user/profile');
$this->assertTrue($client->getResponse()->isRedirect());
$client->request('GET', '/user/profile/edit');
$this->assertTrue($client->getResponse()->isRedirect());
$client->request('GET', '/user/profile/editpassword');
$this->assertTrue($client->getResponse()->isRedirect());
}
public function testUserFormRegister()
{
$client = static::createClient();
$crawler = $client->request('GET', '/user/register');
$buttonCrawlerNode = $crawler->selectButton('submit_user_register');
$form = $buttonCrawlerNode->form();
$testForm = array(
'wineot_databundle_user[username]' => 'test',
'wineot_databundle_user[firstname]' => 'test',
'wineot_databundle_user[lastname]' => 'test',
'wineot_databundle_user[mail]' => 'test#mail.fr',
'wineot_databundle_user[plain_password][first]' => 'blabla321',
'wineot_databundle_user[plain_password][second]' => 'blabla321'
);
$response = $client->getResponse();
$client->submit($form, $testForm);
//If the submit is true that mean that the register is ok
$this->assertTrue($response->isSuccessful());
}
I hope that will help you do undestand how to test.

Create form dynamically in Symfony 2

A simple question:
I have one form, it returns one number and I need create this number of labels in Controller.
I try:
$form2 = $this->createFormBuilder();
for($i = 0; $i < $num; $i++) {
$name = 'column'.$i;
$form2->add($name,'number');
}
$form2->getForm();
I think it should very simple, but i can't..
Yes, you can do it with an array / hash map instead of a real object.
Here is an example :
// Create the array
$dataObj = array();
$dataObj['data1'] = '';
$dataObj['data2'] = 'default';
// ... do a loop here
$dataObj['data6'] = 'Hello';
// Create the form
$formBuilder = $this->createFormBuilder($dataObj);
foreach($dataObj as $key => $val)
{
$fieldType = 'text'; // Here, everything is a text, but you can change it based on $key, or something else
$formBuilder->add($key, $fieldType);
}
$form = $formBuilder->getForm();
// Process the form
$request = $this->get('request');
if($request->getMethod() == 'POST')
{
$form->bind($request); // For symfony 2.1.x
// $form->bind($this->get('request')->request->get('form')); // For symfony 2.0.x
if($form->isValid())
{
$dataObj = $form->getData();
foreach($dataObj as $key => $val)
{
echo $key . ' = ' . $val . '<br />';
}
exit('Done');
}
}
// Render
return $this->render('Aaa:Bbb:ccc.html.twig', array(
'requestForm' => $form->createView()));

Resources