error in mail functionality in laravel 5.3 - laravel-5.3

Im working with laravel 5.3. In that i have mail functionality the variable get after the mail function is not working, below is my controller coding
public function checkEmail(Request $request) {
$email = $request->input('email');
$users = Student::where('email', $email)->select('email')->first();
if(count($users) > 0){
$id =Student::where('email',$email )->value('id');
$url=url('/').'/password-reset/'.$id;
Mail::send('/resetpassword', ['email'=>$email,'url'=>$url ], function($message)
{
$message->to(Input::get('email'))->subject('Reset Password');
});
return redirect()->back()->with('message', 'Link has been sent to your Mail');
} else {
return redirect()->back()->with(['message' => 'No Records Found']);
}
}
I got all the variable values before mail function (i.e.,)
Mail::send('/resetpassword', ['email'=>$email,'url'=>$url ], function($message)
{
$message->to(Input::get('email'))->subject('Reset Password');
});
I got error like this
Class 'App\Http\Controllers\Input' not found
if i use any variable the error is like this
Undefined Variable:url
Please anyone tellme what i did wrong...

Related

Symfony 5 Reset Password how do i get the right url?

I'll try to explain my problem.
I have recently started a new projet and wanted to implement a reset password functionnality.
Everything seems to work except the generation of the url which is send by email.
picture of my URL
My URL should look like this : http://localhost/projectName/public/reset-password/reset/xOdfPc0iGC7nmReqX02jcemgX4EIlt2tb5vNYgTZ
But the "/projectName/public/" is missing.
I don't understand what i did wrong.
Here is my twig template for the email :
<h1>Bonjour !</h1>
<p>Pour réinitialiser votre mot de passe, merci de vous rendre sur le lien suivant</p>
{{ url('app_reset_password', { token: resetToken.token }) }}
<p>Ce lien expirera dans {{ resetToken.expirationMessageKey|trans(resetToken.expirationMessageData, 'ResetPasswordBundle') }}.</p>
<p>A bientôt !</p>
Here is the function in the controller that generates the templated email :
private function processSendingPasswordResetEmail(string $emailFormData, MailerInterface $mailer, TranslatorInterface $translator): RedirectResponse
{
$user = $this->entityManager->getRepository(User::class)->findOneBy([
'email' => $emailFormData,
]);
// Do not reveal whether a user account was found or not.
if (!$user) {
return $this->redirectToRoute('app_check_email');
}
try {
$resetToken = $this->resetPasswordHelper->generateResetToken($user);
} catch (ResetPasswordExceptionInterface $e) {
// If you want to tell the user why a reset email was not sent, uncomment
// the lines below and change the redirect to 'app_forgot_password_request'.
// Caution: This may reveal if a user is registered or not.
//
// $this->addFlash('reset_password_error', sprintf(
// '%s - %s',
// $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
// $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
// ));
return $this->redirectToRoute('app_check_email');
}
$email = (new TemplatedEmail())
->from(new Address('assistance#asintel.com', 'AS Intel - Assistance'))
->to($user->getEmail())
->subject('Your password reset request')
->htmlTemplate('reset_password/email.html.twig')
->context([
'resetToken' => $resetToken,
])
;
$mailer->send($email);
// Store the token object in session for retrieval in check-email route.
$this->setTokenObjectInSession($resetToken);
return $this->redirectToRoute('app_check_email');
}
And this is the function with app_reset_password route :
/**
* Validates and process the reset URL that the user clicked in their email.
*
* #Route("/reset/{token}", name="app_reset_password")
*/
public function reset(Request $request, UserPasswordHasherInterface $userPasswordHasher, TranslatorInterface $translator, string $token = null): Response
{
if ($token) {
// We store the token in session and remove it from the URL, to avoid the URL being
// loaded in a browser and potentially leaking the token to 3rd party JavaScript.
$this->storeTokenInSession($token);
return $this->redirectToRoute('app_reset_password');
}
$token = $this->getTokenFromSession();
if (null === $token) {
throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
}
try {
$user = $this->resetPasswordHelper->validateTokenAndFetchUser($token);
} catch (ResetPasswordExceptionInterface $e) {
$this->addFlash('reset_password_error', sprintf(
'%s - %s',
$translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
$translator->trans($e->getReason(), [], 'ResetPasswordBundle')
));
return $this->redirectToRoute('app_forgot_password_request');
}
// The token is valid; allow the user to change their password.
$form = $this->createForm(ChangePasswordFormType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// A password reset token should be used only once, remove it.
$this->resetPasswordHelper->removeResetRequest($token);
// Encode(hash) the plain password, and set it.
$encodedPassword = $userPasswordHasher->hashPassword(
$user,
$form->get('plainPassword')->getData()
);
$user->setPassword($encodedPassword);
$this->entityManager->flush();
// The session is cleaned up after the password has been changed.
$this->cleanSessionAfterReset();
return $this->redirectToRoute('main_index');
}
return $this->render('reset_password/reset.html.twig', [
'resetForm' => $form->createView(),
]);
}
Does someone have an idea what i should do to fix this problem ?
Thanks a lot

woocommerce 3: removing cart items for logged in users does not work

we are using wordpress JSON API to signon a user and to add / update / remove cart-items. We are doing this with the register_rest_route function.
We use this code to remove a cart item:
function remove_from_cart(WP_REST_Request $req)
{
$resp = null;
$cart_item = $req['cart_item'];
try {
WC()->cart->remove_cart_item($cart_item);
} catch (Exception $e) {
$resp = $e;
}
return rest_ensure_response(new CartResponse());
}
This is working perfectly fine for guests. but as soon as a logged in user tries it, the cart is back to its normal state after a page reload. The response created by new CartResponse() is correctly showing the cart without the removed item. however, after a page reload the item is still there.
As this only happens for logged in users and not for guests I think it is a session issue.
Also, updating the cart with the following method works for logged in users:
function update_cart_item(WP_REST_Request $req)
{
$resp = null;
$cart_item = $req['cart_item'];
try {
if ($cart_item && $cart_item['quantity']) {
WC()->cart->set_quantity($cart_item['key'], $cart_item['quantity']);
}
} catch (Exception $e) {
$resp = $e;
}
return rest_ensure_response(new CartResponse());
}
Unfortunately, setting the quantity to 0 is also not working.
This is how we signon users:
function login_customer(WP_REST_Request $req)
{
$body = $req->get_body();
$input = json_decode($body, TRUE);
$credentials = ['user_login' => $input['email'], 'user_password' => $input['password']];
$user = wp_signon($credentials, false);
if (is_a($user, 'WP_Error') || !$user) {
// if an error occurs, return null
return rest_ensure_response(null);
}
$resp = new CustomerResponse($user->ID);
return rest_ensure_response($resp);
}
And we are not using any caching plugins. What is wrong here?
Here is a list of all session cookies:
EDIT:
I just inspected the cookies while beeing logged in and removing a cart item.
Cart Hash before deleting: bb35785a228a17ceb85f8ed2dc522b16
Cart Hash directly after deleting: d32e22e278d42022e04b6992b7d65816
Cart Hash after page reload: bb35785a228a17ceb85f8ed2dc522b16 again
So it seems like the cart hash is stored somewhere and restored on a reload, but not correctly updated on deleting a cart item
It seems like you need nonces to authenticate DELETE requests.
Now I am adding nonces to each response in a header:
function add_cors_http_header(){
header("X-WP-Nonce: ".wp_create_nonce('wp_rest'));
}
add_action('init','add_cors_http_header');
And in the frontend I set it:
let nonce: string = null;
export const fetchNoAuth = (endpoint: string, method: string = 'GET', data: any = null): Promise<any> => {
let headers: any = {'Content-Type': 'application/json'};
if (nonce) {
headers['X-WP-Nonce'] = nonce;
}
return fetch('http://' + apiUrl + apiPath + endpoint + '?' + debugQuery, {
method,
credentials: 'include',
headers,
body: data ? JSON.stringify(data) : null
})
.then((data) => {
const nonceFromResponse = data.headers.get('X-WP-Nonce');
if (nonceFromResponse) {
nonce = nonceFromResponse;
} else {
nonce = null;
}
return data;
})
};
Make sure that the header in the request is named X-WP-Nonce

Email sending in laravel 5.3

I an using this code in laravel 5.3 for sending email. But it says undefined variable $email, while i have defined the variable already.
This is my code.
$user->save();
if (!empty($user->save())) {
$email = 'ppriyadarshi49#gmail.com';
$mail = Mail::send('email_page', ['verification_key' => $verification_code], function($message) {
$message->from('prince.priyadarshi#fluper.com', 'Verify');
$message->to($email)
->subject('Verify your email address');
});
return view('for_company');
}
And the error is Undefined variable: email
Your are missing use() in closure function as:
$user->save();
if (!empty($user->save())) {
$email = 'ppriyadarshi49#gmail.com';
$mail = Mail::send('email_page', ['verification_key' => $verification_code], function($message) use($email) {
$message->from('prince.priyadarshi#fluper.com', 'Verify');
$message->to($email)
->subject('Verify your email address');
});
return view('for_company');
}

Contact Form 7 sometimes doesn't work

My Contact Form 7 in some period of time doesn't work in other works fine.
I am getting message:
Failed to send your message. Please try later or contact the administrator by another method
I tried to debug this and found that CF7 will call wp_mail.
It will call this code from Contact Form 7:
if ( $send ) {
return #wp_mail( $recipient, $subject, $body, $headers, $attachments );
}
But this will return false.
Hase anyone some idea what can be problem.
EDIT:
When it call wp_mail it will throw error in this part of wordpress code:
if (!$this->smtp->data($header . $body)) {
throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL);
}
EDIT:
This data function will at the first line will call function "sendComand":
public function data($msg_data)
{
if (!$this->sendCommand('DATA', 'DATA', 354)) {
return false;
}
.....
It will failm in this if statment.
Here is sendCommand function:
protected function sendCommand($command, $commandstring, $expect)
{
if (!$this->connected()) {
$this->error = array(
"error" => "Called $command without being connected"
);
return false;
}
$this->client_send($commandstring . self::CRLF);
$reply = $this->get_lines();
$code = substr($reply, 0, 3);
if ($this->do_debug >= 2) {
$this->edebug('SMTP -> FROM SERVER:' . $reply);
}
if (!in_array($code, (array)$expect)) {
$this->last_reply = null;
$this->error = array(
"error" => "$command command failed",
"smtp_code" => $code,
"detail" => substr($reply, 4)
);
if ($this->do_debug >= 1) {
$this->edebug(
'SMTP -> ERROR: ' . $this->error['error'] . ': ' . $reply
);
}
return false;
}.......
and this will fail in this last if statment, this condition in if (!in_array($code, (array)$expect)) will be true.
So $expect was provided on sendCommand function call:
$this->sendCommand('DATA', 'DATA', 354)
(array)$expect) == Array([0] => 354)
and $code we will get from get_lines() function:
$reply = $this->get_lines();
$code = substr($reply, 0, 3);
When it fail in $reply is next value:
$reply = 550 5.4.5 Daily sending quota exceeded. u1sm14669850qat.27 - gsmtp
And here is get_lines() source:
https://github.com/WordPress/WordPress/blob/master/wp-includes/class-smtp.php#L820
I've had this issue before and resolved it by switching to gmail's smtp by using this plugin:
https://wordpress.org/plugins/wp-mail-smtp/faq/
All you need to set it up is a gmail account, if this is a client/work website, you can create a free account with gmail and simply enter it in the plugin settings.

ZF2 - ServiceManager & getServiceConfig problems - unable to fetch or create instance

I am coming across some problems when trying to use ZF2's authentication services. I have to following Module.php getServiceConfig function:
<?php
public function getServiceConfig()
{
return array(
'factories' => array(
'Auth\Model\CustomerTable' => function($sm) {
$tableGateway = $sm->get('CustomerTableGateway');
$table = new CustomerTable($tableGateway);
return $table;
},
'CustomerTableGateway' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Customer()); // prototype pattern implemented.
return new TableGateway('customer', $dbAdapter, null, $resultSetPrototype);
},
'Auth\Model\AuthStorage' => function($sm){
return new \Auth\Model\AuthStorage('jamietech');
},
'AuthService' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter,
'customer','username','password');
$authService = new AuthenticationService();
$authService->setAdapter($dbTableAuthAdapter);
$authService->setStorage($sm->get('Auth\Model\AuthStorage'));
return $authService;
},
),
);
}
The AuthStorage factory simply creates a new AuthStorage for us to keep track of the rememberMe function I have, and the AuthService factory creates a new Authentication Service for us. I can't see anything that I have done wrong but when running the following code in the AuthController.php:
<?php
public function loginAction()
{
//if already login, redirect to success page
if ($this->getAuthService()->hasIdentity()){
return $this->redirect()->toRoute('success');
}
$form = new LoginForm();
return array(
'form' => $form,
'messages' => $this->flashmessenger()->getMessages()
);
}
public function logoutAction()
{
$this->getSessionStorage()->forgetMe();
$this->getAuthService()->clearIdentity();
$this->flashmessenger()->addMessage("You have logged out successfully.");
return $this->redirect()->toRoute('auth', array('action'=>'login'));
}
PHPUnit encounters the following errors when running the PHPUnit command:
1: "testLoginActionCanBeAccessed - Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance of Zend\Db\Adapter\Adapter
1: "testLogoutActionCanBeAccessed - session_regenerate_id(): cannot regenerate session id - headers already sent.
And this error for both login and logout when the -process-isolation command is run:
"Serialization of closure is not allowed in: C;\Users\-----\AppData\Local\Temp\-----
If somebody could help that would be great. I am a ZF noob so try not to be too harsh.
EDIT: BTW THe global.php file includes the service_manager adapter factory illustrated in the ZF2 tutorial application.
Thank you!
Jamie Mclaughlan
did you check these:
autoload_classmap.php (for your module)
in your module.config.php
like this
service_manager' => array(
'aliases' => array(
'mymodule-ZendDbAdapter' => 'Zend\Db\Adapter\Adapter',
),
);
I hope it helps you to find the answer

Resources