src/Controller/RCS/AuthController.php line 215
<?php
namespace App\Controller\RCS;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use App\Entity\Purchase;
use App\Entity\PurchaseItem;
use App\Entity\User;
use App\Entity\Contact;
use App\Entity\Coupon;
use App\Entity\PurchaseNote;
use App\Entity\Product;
use App\Utils\ContentHelper;
use App\Utils\UserHelper;
use App\Utils\ContactHelper;
use App\Utils\EmailHelper;
use App\Utils\OrderHelper;
use App\Utils\LeadHelper;
use App\Security\WordPressPasswordEncoder;
use App\Exception\ResourceNotFoundException;
//use Symfony\Bridge\Doctrine\Security\RememberMe\DoctrineTokenProvider;
use Symfony\Component\Security\Core\Authentication\RememberMe\PersistentToken;
use Symfony\Component\HttpFoundation\Cookie;
//todo: Make a Master AuthController, and combine any other controllers that we can
class AuthController extends DefaultController
{
/**
* @Route("/sign-in",
* name="sign-in-post",
* defaults={"message": ""},
* methods={"POST"}
* )
*/
public function signInPost(
Request $request,
UserHelper $userHelper,
EmailHelper $emailHelper,
//DoctrineTokenProvider $doctrineTokenProvider,
$message = ""
)
{
$username = $request->get("_username");
$password = $request->get("_password");
if(!$emailHelper->checkCaptcha($request->get("g-recaptcha-response"))) {
//$this->addFlash("warning", "The reCAPTCHA was invalid. Please try again.");
$message = array (
"type" => "warning",
"text" => "The reCAPTCHA was invalid. Please try again.",
);
return $this->defaultRender("forms/sign-in.html.twig", [
"message" => $message,
]);
}
$session = $request->getSession();
$nRoute = $session->get("non_sign_in_route");
$path = !empty($nRoute["path"]) ? $nRoute["path"] : "/";
$result = $userHelper->signIn(
$username,
$password
);
if(is_array($result) && $result["status"] == 2) {
return new RedirectResponse("/mfa/{$result['uid']}/{$result['token']}");
}
elseif (is_array($result) && $result["status"] == 1) {
$this->addFlash("success", "You have successfully logged in.");
$response = new RedirectResponse($path);
//$response = $this->setRememberMe($request, $response, $doctrineTokenProvider, $username);
}
else {
$message = array (
"type" => "warning",
"text" => "Invalid credentials provided.",
);
return $this->defaultRender("forms/sign-in.html.twig", [
"message" => $message,
]);
}
return $response;
}
/**
* @Route("/sign-in",
* name="sign-in",
* defaults={"message": ""}
* )
*/
public function signIn(
Request $request,
AuthenticationUtils $authUtils,
WordPressPasswordEncoder $wpEncoder,
$message = ""
) {
//just testing: $message = $wpEncoder->hash("M0byd1ck771!");
//$message = null;
$message = $request->query->get("message") ?? "";
$error = $authUtils->getLastAuthenticationError();
$lastUsername = $authUtils->getLastUsername();
if ($error) {
$message = array (
"type" => "warning",
"text" => "Invalid credentials.",
);
}
return $this->defaultRender("forms/sign-in.html.twig", [
"last_username" => $lastUsername,
// "error" => $error,
"message" => $message,
]);
}
/**
* @Route("/forgot-password", name="forgot-password")
*/
public function forgotPassword (
Request $request,
UserHelper $userHelper,
ContactHelper $contactHelper,
EmailHelper $emailHelper
) {
// should we rate limit ??
$username = $request->request->get("username");
$message = array ();
if ($username) {
$rsp = $userHelper->forgotPassword($username);
$message = array(
"type" => $rsp["status"] ? "success" : "warning",
"text" => $rsp["message"],
);
}
return $this->defaultRender("forms/forgot-password.html.twig", [
"message" => $message,
]);
}
/**
* @Route("/forgot-username", name="forgot-username", methods={"POST"})
*/
public function forgotUsername (
Request $request,
UserHelper $userHelper
) {
$email = $request->get("email");
$rsp = $userHelper->forgotUsername($email);
$msg = array ();
if ($rsp["status"]) {
$msg = array (
"type" => "success",
"text" => $rsp["message"],
);
}
else {
sleep (3);
$msg = array (
"type" => "warning",
"text" => $rsp["message"],
);
}
return $this->defaultRender("forms/forgot-username.html.twig", [
"message" => $msg
]);
/*
try {
$user = $userHelper->getUserByEmail($email);
$username = $user->getUsername();
return $this->defaultRender("forms/sign-in.html.twig", [
"message" => [
"type" => "success",
"text" => "The username linked to that account is <strong>{$username}</strong>.",
]
]);
} catch (ResourceNotFoundException $e) {
sleep(3);
return $this->defaultRender("forms/forgot-username.html.twig", [
"message" => [
"type" => "warning",
"text" => "That e-mail address was not found in the system.",
]
]);
}
*/
}
/**
* @Route("/forgot-username", name="forgot-username-form")
*/
public function viewForgotUsername (
) {
return $this->defaultRender("forms/forgot-username.html.twig", [
"message" => array ()
]);
}
/**
* @Route("/rcs-reset-password/{id}/{token}", name="reset-password-form", defaults={"message": ""})
*/
public function viewResetPassword (
UserHelper $userHelper,
Request $request,
$id,
$token,
$message = ""
) {
try {
$user = $userHelper->getUserById($id);
$message = $request->query->get("message") ?? "";
// if token does not match
if ($token != $user->getResetPwToken()) {
return $this->defaultRender("errors/404.html.twig");
}
return $this->defaultRender("forms/reset-password.html.twig", [
"user" => $user,
"id" => $id,
"token" => $token,
"message" => $message
]);
} catch (ResourceNotFoundException $e) {
}
}
/**
* @Route("/rcs-reset-password", name="reset-password", methods={"POST"})
*/
public function resetPassword (
Request $request,
WordPressPasswordEncoder $wpEncoder,
UserHelper $userHelper
) {
$id = $request->get("id");
$token = $request->get("token");
$password1 = $request->get("password1");
$password2 = $request->get("password2");
$rsp = $userHelper->resetPassword(
$id,
$token,
$password1,
$password2
);
$msg = array ();
if ($rsp["status"]) {
$msg = array (
"type" => "success",
"text" => $rsp["message"],
);
return $this->redirectToRoute("sign-in", [
"message" => $msg
]);
}
else {
$msg = array (
"type" => "warning",
"text" => $rsp["message"],
);
return $this->redirectToRoute("reset-password-form", [
"id" => $id,
"token" => $token,
"message" => $msg
]);
}
}
/* *
* @ R o u t e ("/rcs-sign-up", name="sign-up", methods={"POST"})
* /
public function signUp (
Request $request,
UserHelper $userHelper,
EmailHelper $emailHelper
) {
$username = $request->get("username");
$email = $request->get("email");
if($emailHelper->checkCaptcha($request->get("g-recaptcha-response"))) {
$password1 = $request->get("password1");
$password2 = $request->get("password2");
$rsp = $userHelper->signUp(
$username,
$email,
$password1,
$password2
);
if ($rsp["status"]) {
return $this->defaultRender("forms/sign-in.html.twig", [
"message" => $rsp["message"],
]);
}
return $this->defaultRender("forms/sign-up.html.twig", [
"username" => $username,
"email" => $email,
"message" => $rsp["message"],
]);
}
else {
return $this->defaultRender("forms/sign-up.html.twig", [
"username" => $username,
"email" => $email,
"message" => [
"type" => "warning",
"text" => "The reCAPTCHA was invalid. Please try again.",
],
]);
}
}
*/
/* *
* @ R o u t e("/rcs-sign-up", name="sign-up-form")
* /
public function viewSignUp (
) {
return $this->defaultRender("forms/sign-up.html.twig", [
"username" => "",
"email" => "",
"message" => array (
)
]);
}
*/
/**
* @Route("/sign-up", name="new-sign-up", methods={"POST"})
*/
public function newSignUp (
Request $request,
UserHelper $userHelper,
EmailHelper $emailHelper,
LeadHelper $leadHelper,
ContentHelper $contentHelper
) {
if(!$emailHelper->checkCaptcha($request->get("g-recaptcha-response"))) {
$lead = $request->get("lead");
$firstname = array_key_exists("firstname", $lead) ? $lead["firstname"] : "";
$lastname = array_key_exists("lastname", $lead) ? $lead["lastname"] : "";
$email = array_key_exists("email", $lead) ? $lead["email"] : "";
$username = array_key_exists("username", $lead) ? $lead["username"] : "";
$address1 = array_key_exists("address1", $lead) ? $lead["address1"] : "";
$address2 = array_key_exists("address2", $lead) ? $lead["address2"] : "";
$city = array_key_exists("city", $lead) ? $lead["city"] : "";
$state = array_key_exists("state", $lead) ? $lead["state"] : "";
$zip = array_key_exists("zip", $lead) ? $lead["zip"] : "";
$company = array_key_exists("company", $lead) ? $lead["company"] : "";
$phone = array_key_exists("phone", $lead) ? $lead["phone"] : "";
//$this->addFlash("warning", "The reCAPTCHA was invalid. Please try again.");
return $this->defaultRender("forms/new-sign-up.html.twig", [
"username" => $username,
"email" => $email,
"firstname" => $firstname,
"lastname" => $lastname,
"address1" => $address1,
"address2" => $address2,
"city" => $city,
"state" => $state,
"zip" => $zip,
"company" => $company,
"phone" => $phone,
"message" => [
"type" => "warning",
"text" => "The reCAPTCHA was invalid. Please try again.",
]
]);
}
$siteSignup = $request->get("site-signup");
$enewsSignup = $request->get("enews-signup");
//$enewsMetalSignup = $request->get("enews-metal-signup");
$enewsSignupSuccess = false; //store if they signed up for the enews
$enewsMetalSignupSuccess = false; //store if they signed up for metal enews
$siteSignupSuccess = false; //store if they signed up for the site
if($siteSignup) {
//Handle the form for signing up to the site.
$lead = $request->get("lead");
$username = $lead["username"];
$email = $lead["email"];
$email = trim($email);
$firstname = $lead["firstname"];
$lastname = $lead["lastname"];
$address1 = $lead["address1"];
$address2 = $lead["address2"];
$city = $lead["city"];
$state = $lead["state"];
$zip = $lead["zip"];
$company = $lead["company"];
$phone = $lead["phone"];
$password1 = $request->get("password1");
$password2 = $request->get("password2");
$rsp = $userHelper->signUp(
$firstname,
$lastname,
$username,
$email,
$password1,
$password2
);
if ($rsp["status"]) { //success
$siteSignupSuccess = true;
//return new RedirectResponse('/welcome-activation');
}
else {
//$this->addFlash("warning", $rsp["message"]);
return $this->defaultRender("forms/new-sign-up.html.twig", [
"username" => $username,
"email" => $email,
"firstname" => $firstname,
"lastname" => $lastname,
"address1" => $address1,
"address2" => $address2,
"city" => $city,
"state" => $state,
"zip" => $zip,
"company" => $company,
"phone" => $phone,
"message" => $rsp["message"],
]);
}
}
if ($enewsSignup || ($siteSignup && $siteSignupSuccess && ($request->get("enews") || $request->get("metal-enews") || $request->get("coatings-enews")))) {
//Handle the form for signing up for just enews-signup
$lead = $request->get("lead");
$firstname = $lead["firstname"];
$lastname = $lead["lastname"];
$email = $lead["email"];
$email = trim($email);
$company = $lead["company"];
$contractor_type = $lead["contractor_type"];
$country = ($lead["country"] == "Other" ? $lead["country_other"] : $lead["country"]);
$business_type = $lead["business_type"];
if(empty($email) || filter_var($email, FILTER_VALIDATE_EMAIL) === false){
$this->addFlash("warning", "Please enter a valid email address.");
return new RedirectResponse($request->headers->get('referer'));
}
if(empty($firstname)){
$this->addFlash("warning", "Please enter your first name");
return new RedirectResponse($request->headers->get('referer'));
}
if(empty($lastname)){
$this->addFlash("warning", "Please enter your last name");
return new RedirectResponse($request->headers->get('referer'));
}
if(empty($company)){
$this->addFlash("warning", "Please enter your company");
return new RedirectResponse($request->headers->get('referer'));
}
try {
//add to mailchimp list
// MailChimp API credentials
$apiKey = "27ce559264a47aa3487224e1c95424bc-us10";
$listID = "3efdbc4139";
// Determine wir wim or both
$keys = [];
if ($request->get("enews")) {
array_push($keys, 'WIR');
}
if ($request->get("metal-enews")) {
array_push($keys, 'WIM');
}
if ($request->get("coatings-enews")) {
array_push($keys, 'WIC');
}
// MailChimp API URL
$memberID = md5(strtolower($email));
$dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listID . '/members/' . $memberID;
// member information
$json = json_encode([
'email_address' => $email,
'status' => 'subscribed',
'merge_fields' => [
'FNAME' => $firstname,
'LNAME' => $lastname,
'MMERGE3' => $company,
'MMERGE4' => $contractor_type,
'MMERGE5' => $business_type
],
'tags' => $keys
]);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode != 200) {
$httpErrorCode = $httpCode;
}
// end mailchimp
if ($request->get("enews")) {
$emailHelper->sendEmail(
["rcs@rooferscoffeeshop.com"],
"New submission from the \"Week in Roofing\" sign-up form.",
[
["p" => "New submission from the \"Week in Roofing\" sign-up form."],
["table" => [
"First Name" => $firstname,
"Last Name" => $lastname,
"Email Address" => $email,
"Company" => $company,
"Country" => $country,
"Type of Work" => $contractor_type,
"Type of Business" => $business_type,
]],
]
);
}
if ($request->get("metal-enews")) {
$emailHelper->sendEmail(
["rcs@rooferscoffeeshop.com"],
"New submission from the \"Week in Metal\" sign-up form.",
[
["p" => "New submission from the \"Week in Metal\" sign-up form."],
["table" => [
"First Name" => $firstname,
"Last Name" => $lastname,
"Email Address" => $email,
"Company" => $company,
"Country" => $country,
"Type of Work" => $contractor_type,
"Type of Business" => $business_type,
]],
]
);
}
if ($request->get("coatings-enews")) {
$emailHelper->sendEmail(
["rcs@rooferscoffeeshop.com"],
"New submission from the \"Week in Coatings\" sign-up form.",
[
["p" => "New submission from the \"Week in Coatings\" sign-up form."],
["table" => [
"First Name" => $firstname,
"Last Name" => $lastname,
"Email Address" => $email,
"Company" => $company,
"Country" => $country,
"Type of Work" => $contractor_type,
"Type of Business" => $business_type,
]],
]
);
}
// store the lead
$content = null;
$lead_custom = $request->get("lead_custom");
$lead = $leadHelper->saveLead($lead, $content, $request, $lead_custom);
if(isset($httpErrorCode)) {
$lead->setComments("MailChimp http code: {$httpErrorCode}");
}
$em = $this->getDoctrine()->getManager();
$em->persist($lead);
$em->flush();
if(isset($httpErrorCode)) {
$this->addFlash("warning", "An error occurred while attempting to add you to our mailing list. Please try again later.");
return new RedirectResponse($request->headers->get('referer'));
}
//$this->addFlash("success", "Thank you for signing up for the RCS Week in Review.");
//return new RedirectResponse($request->headers->get('referer'));
$enewsSignupSuccess = true;
}
catch (\Exception $e) {
$this->addFlash("warning", $e->getMessage());
return new RedirectResponse($request->headers->get('referer'));
}
}
else {
$lead = $request->get("lead");
$lead_custom = $request->get("lead_custom");
$lead = $leadHelper->saveLead($lead, null, $request, $lead_custom);
$em = $this->getDoctrine()->getManager();
$em->persist($lead);
$em->flush();
}
if($siteSignupSuccess) {
return new RedirectResponse('/welcome-activation');
}
if($enewsSignupSuccess) {
// $this->addFlash("success", "Thank you for signing up for the RCS Week in Roofing.");
return new RedirectResponse('/thank-you-wir');
}
}
/**
* @Route("/sign-up", name="new-sign-up-form")
*/
public function viewNewSignUp (
) {
return $this->defaultRender("forms/new-sign-up.html.twig", [
"firstname" => "",
"lastname" => "",
"username" => "",
"email" => "",
"address1" => "",
"address2" => "",
"city" => "",
"state" => "",
"zip" => "",
"company" => "",
"message" => array (
),
"meta" => array (
"breadcrumbs" => [
[
"title" => "Sign Up",
"href" => "/sign-up",
]
]
)
]);
}
/**
* @Route("/activate-account", name="activate", methods={"POST"})
*/
public function activateAccount (
Request $request,
UserHelper $userHelper,
ContentHelper $contentHelper
) {
$id = $request->get("id");
$token = $request->get("token");
$rclubProdId = $request->get("rclubProdId");
$rsp = $userHelper->activateAccount($id, $token);
if ($rsp["status"]) {
//redirect to purchase page if rclubProdId is set
if($rclubProdId) {
$user = $userHelper->getUserById($id);
if ($user) {
// use the current cart or create one
$purchase = $user->getActivePurchase();
if (!$purchase) {
$purchase = new Purchase();
}
//Remove all items since we're going straight to checkout
foreach($purchase->getItems() as $item) {
//$product = $item->getProduct();
//if($product->getType() == Product::PRODUCT_TYPE_MEMBERSHIP) {
$purchase->removeItem($item);
//}
}
$newItem = new PurchaseItem();
$newItem->setProduct($contentHelper->getProductById($rclubProdId));
$newItem->setType(PurchaseItem::TYPE_MEMBERSHIP);
$newItem->setPurchase($purchase);
// add to the current Item
$purchase->setCurrentItem($newItem);
$purchase->setUser($user);
$purchase->setDiscount(0);
$manager = $this->getDoctrine()->getManager();
$manager->persist($purchase);
$manager->flush();
$this->addFlash("success", "You have successfully activated your account! Please complete your purchase below to join the R-Club.");
return $this->redirectToRoute("purchase", [
]);
}
}
/*return $this->defaultRender("/", [
"message" => array (
"type" => "success",
"text" => $rsp["message"],
)
]);*/
//$this->addFlash("success", $rsp["message"]);
//return $this->redirect("/");
return $this->redirect("/welcome-to-rcs");
//$this->addFlash("success", $rsp["message"]);
//return $this->redirect('http://staging.rooferscoffeeshop.com/post-a-classified-ad/2');
}
else {
return $this->defaultRender("forms/send-activation.html.twig", [
"type" => "warning",
"text" => $rsp["message"],
]);
}
/*
try {
$id = $request->get("id");
$token = $request->get("token");
$user = $userHelper->getUserById($id);
$expires = $user->getActivationExpires();
if ($user->getActivationToken() == $token &&
new \DateTime("now") < $expires
) {
$user->setActivationToken(null);
$user->setActivationExpires(null);
// $user->setIsActive(1);
$user->setStatus(1);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$em->clear();
return $this->defaultRender("forms/sign-in.html.twig", [
"message" => array (
"type" => "success",
"text" => "The account has been activated. You may now sign in.",
),
]);
}
}
catch (ResourceNotFoundException $e) {
// ... ignore
}
return $this->defaultRender("forms/send-activation.html.twig", [
"message" => array (
"type" => "warning",
"text" => "The provided token was not found in the system. It is possible that it has expired. If the token has expired, you will need to sign up again.",
),
]);
*/
}
/**
* @Route("/activate-account/{id}/{token}/{rclubProdId}", name="view-activation-form")
*/
public function viewActivateAccount (
UserHelper $userHelper,
$id = "",
$token = "",
$rclubProdId = ""
) {
try {
$user = $userHelper->getUserById($id);
$expires = $user->getActivationExpires();
if ($token == $user->getActivationToken() &&
new \DateTime("now") < $expires
) {
return $this->defaultRender("forms/activate.html.twig", [
"username" => $user->getUsername(),
"id" => $id,
"token" => $token,
"rclubProdId" => $rclubProdId,
]);
}
} catch (ResourceNotFoundException $e) {
// ... ignore
}
return $this->defaultRender("forms/send-activation.html.twig", [
"message" => array (
"type" => "warning",
"text" => "The provided token was not found in the system. It is possible that it has expired. If the token has expired, you will need to sign up again or re-send the activation link.",
),
]);
}
/**
* @Route("/send-activation", name="send-activation", methods={"POST"})
*/
public function sendActivation (
Request $request,
UserHelper $userHelper,
EmailHelper $emailHelper
) {
$email = $request->get("email");
$resp = $userHelper->sendActivation($email);
if ($resp["status"]) {
return $this->defaultRender("forms/send-activation.html.twig", [
"message" => array (
"type" => "success",
"text" => $resp["message"],
)
]);
}
return $this->defaultRender("forms/send-activation.html.twig", [
"message" => array (
"type" => "warning",
"text" => $resp["message"],
)
]);
/*
try {
$email = $request->get("email");
$user = $userHelper->getUserByEmail($email);
$uid = $user->getId();
$token = $user->getActivationToken();
$expires = $user->getActivationExpires();
$pooled = $emailHelper->sendEmail($email, "Account Activation Link", [
["p" => "Hello {$user->getFullName()},"],
["p" => "You recently requested to receive an activation link for your RoofersCoffeeShop account. Click the button below to activate it."],
["button" => [
"text" => "Activate Account",
"href" => "https://rooferscoffeeshop.com/activate-account/{$uid}/{$token}",
]],
["p" => "If you did not request a password reset, please ignore this email or reply to let us know. This password reset link is only valid for the next 2 hours."],
]);
if ($pooled) {
return $this->defaultRender("forms/send-activation.html.twig", [
"message" => array (
"type" => "success",
"text" => "The activation link has been sent to that e-mail address.",
)
]);
}
return $this->defaultRender("forms/send-activation.html.twig", [
"message" => array (
"type" => "warning",
"text" => "An error occurred while trying to send a system e-mail. If this error continues to occur please contact support.",
)
]);
} catch (ResourceNotFoundException $e) {
}
return $this->defaultRender("forms/send-activation.html.twig", [
"message" => array (
"type" => "warning",
"text" => "No account found matching that criteria.",
)
]);
*/
}
/**
* @Route("/send-activation", name="send-activation-form")
*/
public function viewSendActivation (
UserHelper $userHelper
) {
return $this->defaultRender("forms/send-activation.html.twig", [
"message" => array (),
]);
}
/**
* @Route("/mfa/{id}/{token}", name="view-mfa-form")
*/
public function viewMfa (
UserHelper $userHelper,
$id = "",
$token = ""
) {
try {
$user = $userHelper->getUserById($id);
$expires = $user->getMfaTokenExpires();
if ($token == $user->getMfaToken() &&
new \DateTime("now") < $expires
) {
return $this->defaultRender("forms/mfa.html.twig", [
"username" => $user->getUsername(),
"id" => $id,
"token" => $token,
]);
}
} catch (ResourceNotFoundException $e) {
// ... ignore
}
return $this->defaultRender("forms/sign-in.html.twig", [
"message" => array (
"type" => "warning",
"text" => "The provided token was not found in the system. It is possible that it has expired. Try signing in again.",
),
]);
}
/**
* @Route("/mfasignin", name="mfasignin", methods={"POST"})
*/
public function mfaSignIn (
Request $request,
UserHelper $userHelper
//DoctrineTokenProvider $doctrineTokenProvider
) {
$id = $request->get("id");
$token = $request->get("token");
$code = $request->get("code");
$rsp = $userHelper->signInMfa($id, $token, $code);
if ($rsp["status"]) {
/*return $this->defaultRender("/", [
"message" => array (
"type" => "success",
"text" => $rsp["message"],
)
]);*/
$session = $request->getSession();
$nRoute = $session->get("non_sign_in_route");
$path = !empty($nRoute["path"]) ? $nRoute["path"] : "/";
$user = $userHelper->getUserById($id);
$username = $user->getUsername();
$this->addFlash("success", "You have successfully logged in.");
$response = new RedirectResponse($path);
//$response = $this->setRememberMe($request, $response, $doctrineTokenProvider, $username);
return $response;
//return $this->redirect("/");
//$this->addFlash("success", $rsp["message"]);
//return $this->redirect('http://staging.rooferscoffeeshop.com/post-a-classified-ad/2');
}
else {
return $this->defaultRender("forms/mfa.html.twig", [
//"username" => $user->getUsername(),
"id" => $id,
"token" => $token,
"message" => array (
"type" => "warning",
"text" => $rsp["message"],
)
]);
}
}
//no longer used
public function setRememberMe(
$request,
$response,
$doctrineTokenProvider,
$username
) {
return false;
$series = base64_encode(random_bytes(64));
$tokenValue = base64_encode(random_bytes(64));
$user = $this->user;
$doctrineTokenProvider->createNewToken(
new PersistentToken(
User::class,
//$user->getUsername(),
$username,
$series,
$tokenValue,
new \DateTime()
)
);
$options = [
'name' => 'REMEMBERME',
'lifetime' => 604800,
'path' => '/',
//'domain' => 'staging.rooferscoffeeshop.com',
'domain' => null,
'secure' => true,
'httponly' => true,
'samesite' => 'strict',
];
//samesite =
//public const SAMESITE_NONE = 'none';
//public const SAMESITE_LAX = 'lax';
//public const SAMESITE_STRICT = 'strict';
$cookieParts = [$series, $tokenValue];
foreach ($cookieParts as $cookiePart) {
if (str_contains($cookiePart, ":")) {
throw new \InvalidArgumentException(sprintf('$cookieParts should not contain the cookie delimiter "%s".', ":"));
}
}
$encodedCookie = base64_encode(implode(":", $cookieParts));
//$response = new Response();
$response->headers->setCookie(
new Cookie(
$options['name'],
//$this->encodeCookie([$series, $tokenValue]),
$encodedCookie,
time() + $options['lifetime'],
$options['path'],
$options['domain'],
$options['secure'] ?? $request->isSecure(),
$options['httponly'],
false,
$options['samesite']
)
);
return $response;
}
/**
* @Route("/account", methods={"POST"}, name="post-account")
*/
public function updateAccount (
Request $request,
UserHelper $userHelper
) {
// if we have a current user
if ($this->user) {
// grab the fields
$data = [];
if ($request->get("firstname")) {
$data["firstname"] = $request->get("firstname");
}
if ($request->get("lastname")) {
$data["lastname"] = $request->get("lastname");
}
if ($request->get("displayname")) {
$data["displayname"] = $request->get("displayname");
}
if ($request->get("username")) {
$data["username"] = $request->get("username");
}
if ($request->get("email")) {
$data["email"] = $request->get("email");
}
if ($request->get("password1")) {
$data["password1"] = $request->get("password1");
$data["password2"] = $request->get("password2");
$data["password3"] = $request->get("password3");
}
// user avatar
if ($request->files->get("avatar")) {
$data["avatar"] = $request->files->get("avatar");
$mime = $data["avatar"]->getMimeType();
if(!in_array($mime, ["image/jpg", "image/jpeg", "image/png", "image/gif"])) {
$this->addFlash("danger", "Only PNG, JPG, and GIF file types are allowed.");
return new RedirectResponse($request->headers->get('referer'));
}
}
else if ($request->get("remove_avatar")) {
$data["remove_avatar"] = true;
}
//Update notifications
$data["usermeta"] = [];
$notifications = $request->get("notifications");
if(empty($notifications)) {
$notifications = [];
}
$data["usermeta"]["member_notification_forum"] = in_array("forum", $notifications);
$data["usermeta"]["member_notification_page"] = in_array("page", $notifications);
$data["usermeta"]["member_notification_classifieds"] = in_array("classifieds", $notifications);
$rsp = $userHelper->updateAccount(
$this->user->getId(),
$data
);
$this->addFlash($rsp["type"], $rsp["message"]);
}
return $this->redirectToRoute("account");
}
/**
* @Route("/account/profile", methods={"POST"}, name="post-account-profile")
*/
public function updateAccountProfile (
Request $request,
ContactHelper $contactHelper,
EmailHelper $emailHelper
) {
$user = $this->user;
// if we have a current user
if($user) {
$contact = $user->getContact();
if(!$contact) {
$contact = new Contact();
$user->setContact($contact);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
}
$contactHelper->updateContact($contact->getId(), $request->request->all());
$this->addFlash("success", "Profile updated.");
$emailHelper->sendEmail(
["rcs@rooferscoffeeshop.com"],
"Profile Updated - {$user->getUsername()}",
[
["p" => "{$user->getUsername()} has updated their account's profile information."],
["p" => "Visit the User Dashboard to view these changes."],
["button" => [
"text" => "User Dashboard",
"href" => "https://www.rooferscoffeeshop.com/user-dashboard",
]],
]
);
}
return $this->redirectToRoute("account", [
"slug" => "profile",
]);
}
/**
* @Route("/account/content/{type}", name="account-content-filter")
*/
public function viewAccountContentType (
Request $request,
UserHelper $userHelper,
$type = ""
) {
if (!$this->user) {
return $this->redirect("/sign-in");
}
$user = $this->user;
return $this->defaultRender("forms/user-account.html.twig", [
"user" => $user,
"slug" => "content",
"type" => $type,
"meta" => [
"breadcrumbs" => [
[
"title" => "Your Account",
"href" => "/account",
]
]
]
]);
}
/**
* @Route("/account/membership/cancel", methods={"POST"}, name="post-account-membership-cancel")
*/
public function cancelAccountMembership (
Request $request,
UserHelper $userHelper,
OrderHelper $orderHelper,
EmailHelper $emailHelper
) {
if (!$this->user) {
return $this->redirect("/sign-in");
}
$user = $this->user;
$manager = $this->getDoctrine()->getManager();
$item = $manager->getRepository(PurchaseItem::class)
->findOneBy([
"id" => $request->get("item_id"),
]);
$item->setStatus(PurchaseItem::STATUS_ACTIVE);
$manager->persist($item);
$manager->flush();
//send email
$message = [];
$message[] = ["p" => "Your R-Club membership has been cancelled and will not auto-renew."];
$message[] = ["a" => ["href" => "rooferscoffeeshop.com/account", "text" => "Go to your account page to turn auto-renew back on or update your settings."]];
$emailHelper->sendEmail (
[$user->getEmail()],
"R-Club Auto-Renew Cancelled",
$message
);
$this->addFlash("success", "Your membership has been cancelled and will not auto-renew.");
return $this->redirectToRoute("account", [
"slug" => "membership",
]);
}
/**
* @Route("/account/membership/continue", methods={"POST"}, name="post-account-membership-continue")
*/
public function continueAccountMembership (
Request $request,
UserHelper $userHelper,
OrderHelper $orderHelper,
EmailHelper $emailHelper
) {
if (!$this->user) {
return $this->redirect("/sign-in");
}
$user = $this->user;
$manager = $this->getDoctrine()->getManager();
$item = $manager->getRepository(PurchaseItem::class)
->findOneBy([
"id" => $request->get("item_id"),
]);
$item->setStatus($item->getPaymentFailed() ? PurchaseItem::STATUS_ACTIVE_RENEWING_FINAL : PurchaseItem::STATUS_ACTIVE_RENEWING);
$manager->persist($item);
$manager->flush();
//send email
$message = [];
$message[] = ["p" => "Thank you for re-activating your R-Club membership."];
$message[] = ["a" => ["href" => "rooferscoffeeshop.com/account", "text" => "Go to your account page to view your renewal information."]];
$emailHelper->sendEmail (
[$user->getEmail()],
"R-Club Auto-Renew Activated",
$message
);
$this->addFlash("success", "Your membership has been re-activated and will now automatically renew.");
return $this->redirectToRoute("account", [
"slug" => "membership",
]);
}
/**
* @Route("/account/membership", methods={"POST"}, name="post-account-membership")
*/
public function updateAccountMembership (
Request $request,
UserHelper $userHelper,
OrderHelper $orderHelper
) {
if (!$this->user) {
return $this->redirect("/sign-in");
}
$user = $this->user;
$payment = $request->get("payment");
$card = $request->get("card");
//expiration date
$card["card_expires"] = $card["card_expires_month"].$card["card_expires_year"];
if (!$payment || !isset($payment["terms"])) {
$this->addFlash("warning", "You must accept the terms and conditions.");
return $this->redirectToRoute("account", [
"slug" => "membership",
]);
}
$result = $orderHelper->generateToken(
$payment["firstname"],
$payment["lastname"],
$payment["company"],
$payment["address1"],
$payment["address2"],
$payment["city"],
$payment["state"],
$payment["zip"],
$payment["country"],
$payment["email"],
$payment["phone"],
$_SERVER["REMOTE_ADDR"],
$card["card_number"],
$card["card_expires"],
$card["card_csc"]
);
if ($result["result"] == "APPROVAL" || $result["result"] == "APPROVED") {
$last4 = $card["card_number"];
$last4 = preg_replace("/[^0-9]/", '', $last4);
$last4 = substr($last4, -4);
$user->setUsermetum("has_payment_info", "1");
$user->setUsermetum("payment_first_name", $payment["firstname"]);
$user->setUsermetum("payment_last_name", $payment["lastname"]);
$user->setUsermetum("payment_company", $payment["company"]);
$user->setUsermetum("payment_address_line_1", $payment["address1"]);
$user->setUsermetum("payment_address_line_2", $payment["address2"]);
$user->setUsermetum("payment_city", $payment["city"]);
$user->setUsermetum("payment_state_province", $payment["state"]);
$user->setUsermetum("payment_postal_code", $payment["zip"]);
$user->setUsermetum("payment_country", $payment["country"]);
$user->setUsermetum("payment_email", $payment["email"]);
$user->setUsermetum("payment_phone", $payment["phone"]);
$user->setUsermetum("payment_last4", $last4);
$user->setUsermetum("payment_exp", $card["card_expires"]);
//$user->setUsermetum("payment_cvv2", $card["card_csc"]);
$user->setUsermetum("payment_token", $result["token"]);
$user->setUsermetum("payment_token_response", $result["token_response"]);
$manager = $this->getDoctrine()->getManager();
$manager->persist($user);
$manager->flush();
$this->addFlash("success", "Membership settings updated.");
return $this->redirectToRoute("account", [
//"slug" => "membership",
]);
}
else {
$this->addFlash("warning", "Their was an error while updating your payment information. Response: {$result["result"]}");
return $this->redirectToRoute("account", [
"slug" => "membership",
]);
}
}
/**
* @Route("/account/{slug}/{id}",
* name="account",
* defaults={"slug": "", "id": ""}
* )
*/
public function viewAccount (
UserHelper $userHelper,
Request $request,
$slug = "",
$id = ""
) {
if (!$this->user) {
return $this->redirect("/sign-in");
}
$user = $this->user;
$manager = $this->getDoctrine()->getManager();
$purchases = $user->getPurchases();
$purchase = null;
if (!$slug) {
$slug = "account";
}
if ($slug == "order" && $id) {
// show the order details
$purchase = $manager->getRepository(Purchase::class)
->findOneBy([
"id" => $id
]);
if (!$purchase || $purchase->getUser()->getId() != $user->getId()) {
$purchase = null;
}
}
$customers = $user->getCompanies();
$membership_item = "";
$membership_product = "";
$will_renew = false;
//Get the current purchase item used to activate the user's membership
if($user->isMember()) {
$now = new \DateTime();
foreach($purchases as $p) {
$items = $p->getItems();
foreach($items as $item) {
if(($item->getStatus() >= PurchaseItem::STATUS_ACTIVE) && ($item->getType() == PurchaseItem::TYPE_MEMBERSHIP) && ($item->getExpiresAt() > $now)) {
$membership_item = $item;
$membership_product = $item->getProduct();
$will_renew = ($item->getStatus() >= PurchaseItem::STATUS_ACTIVE_RENEWING ? true : false);
}
}
}
}
$payment = false;
if($slug == "membership") {
if($user->getUserMetaValueByKey("has_payment_info")) {
$payment = [];
$payment["firstname"] = $user->getUserMetaValueByKey("payment_first_name");
$payment["lastname"] = $user->getUserMetaValueByKey("payment_last_name");
$payment["company"] = $user->getUserMetaValueByKey("payment_company");
$payment["address1"] = $user->getUserMetaValueByKey("payment_address_line_1");
$payment["address2"] = $user->getUserMetaValueByKey("payment_address_line_2");
$payment["city"] = $user->getUserMetaValueByKey("payment_city");
$payment["state"] = $user->getUserMetaValueByKey("payment_state_province");
$payment["zip"] = $user->getUserMetaValueByKey("payment_postal_code");
$payment["country"] = $user->getUserMetaValueByKey("payment_country");
$payment["email"] = $user->getUserMetaValueByKey("payment_email");
$payment["phone"] = $user->getUserMetaValueByKey("payment_phone");
}
}
return $this->defaultRender("forms/user-account.html.twig", [
"user" => $user,
"purchases" => $purchases,
"purchase" => $purchase,
"slug" => $slug,
"customers" => $customers,
"membership_item" => $membership_item,
"membership_product" => $membership_product,
"will_renew" => $will_renew,
"payment" => $payment,
"meta" => [
"breadcrumbs" => [
[
"title" => "Your Account",
"href" => "/account",
]
]
]
]);
}
/**
* @Route("/admin-account/membership/{id}", methods={"GET"}, name="admin-account-membership")
*/
public function adminAccountMembership(
Request $request,
UserHelper $userHelper,
$id = ""
) {
//Admin check
$access = false;
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$user = $this->getUser();
if($user) {
if($user->isAdmin()) {
$access = true;
}
}
}
if(!$access) {
$this->addFlash("warning", "This page is only accessible to site administrators.");
return $this->redirectToRoute("/");
}
$member = "";
if($id) {
$member = $userHelper->getUserById($id);
}
$manager = $this->getDoctrine()->getManager();
$purchases = $member->getPurchases();
$purchase = null;
$membership_item = "";
$membership_product = "";
$will_renew = false;
$last_membership_item = "";
$last_membership_product = "";
$renewal_price = "";
//Get the current purchase item used to activate the user's membership
if($member->isMember()) {
$now = new \DateTime();
foreach($purchases as $p) {
$items = $p->getItems();
foreach($items as $item) {
if(($item->getStatus() >= PurchaseItem::STATUS_ACTIVE) && ($item->getType() == PurchaseItem::TYPE_MEMBERSHIP) && ($item->getExpiresAt() > $now)) {
$membership_item = $item;
$membership_product = $item->getProduct();
$will_renew = ($item->getStatus() >= PurchaseItem::STATUS_ACTIVE_RENEWING ? true : false);
$renewal_price = $membership_product->getPrice();
$old_coupons = $p->getCoupons();
foreach($old_coupons as $coupon) {
if($coupon->getProductType() == Coupon::PRODUCT_TYPE_MEMBERSHIP
&& ($coupon->getRecurringType() == Coupon::RECURRING_UNLIMITED
|| ($coupon->getRecurringType() == Coupon::RECURRING_SET_MONTHS && $coupon->getMonthsRecurring() > $item->getMonthsRenewed()))
) {
switch ($coupon->getType()) {
case Coupon::TYPE_DISCOUNT:
$amount = $coupon->getAmount();
if (strpos($amount, ".") === false) {
$amount = "{$amount}00";
}
$amount = preg_replace("/[^0-9]*/", "", $amount);
$renewal_price = $renewal_price - (double)$amount;
break;
case Coupon::TYPE_PERCENTAGE:
$amount = $coupon->getAmount();
$amount = (double) $amount / 100;
$amount = ($renewal_price * $amount);
$renewal_price = $renewal_price - $amount;
break;
case Coupon::TYPE_FREE_PRODUCT:
$couponProducts = $coupon->getProducts();
if ($couponProducts->contains($membership_product)) {
$renewal_price = 0;
}
break;
}
break;
}
}
}
}
}
}
else {
//Get the most recent purchase item used to activate the user's membership
$now = new \DateTime();
foreach($purchases as $p) {
if(!$last_membership_item) {
$items = $p->getItems();
foreach($items as $item) {
if(($item->getStatus() == PurchaseItem::STATUS_INACTIVE) && ($item->getType() == PurchaseItem::TYPE_MEMBERSHIP) && ($item->getExpiresAt() < $now)) {
$last_membership_item = $item;
$last_membership_product = $item->getProduct();
$renewal_price = $last_membership_product->getPrice();
break;
}
}
}
}
}
if($renewal_price) {
if($renewal_price < 0) {
$renewal_price = 0;
}
$renewal_price = "$" . number_format(($renewal_price / 100), 2);
}
$payment = false;
if($member->getUserMetaValueByKey("has_payment_info")) {
$payment = [];
$payment["firstname"] = $member->getUserMetaValueByKey("payment_first_name");
$payment["lastname"] = $member->getUserMetaValueByKey("payment_last_name");
$payment["company"] = $member->getUserMetaValueByKey("payment_company");
$payment["address1"] = $member->getUserMetaValueByKey("payment_address_line_1");
$payment["address2"] = $member->getUserMetaValueByKey("payment_address_line_2");
$payment["city"] = $member->getUserMetaValueByKey("payment_city");
$payment["state"] = $member->getUserMetaValueByKey("payment_state_province");
$payment["zip"] = $member->getUserMetaValueByKey("payment_postal_code");
$payment["country"] = $member->getUserMetaValueByKey("payment_country");
$payment["email"] = $member->getUserMetaValueByKey("payment_email");
$payment["phone"] = $member->getUserMetaValueByKey("payment_phone");
}
return $this->defaultRender("forms/account/admin-membership.html.twig", [
"id" => $id,
"member" => $member,
"purchases" => $purchases,
"purchase" => $purchase,
"membership_item" => $membership_item,
"membership_product" => $membership_product,
"last_membership_item" => $last_membership_item,
"last_membership_product" => $last_membership_product,
"will_renew" => $will_renew,
"renewal_price" => $renewal_price,
"payment" => $payment,
]);
}
/**
* @Route("/admin-account/membership-cancel", methods={"POST"}, name="post-admin-account-membership-cancel")
*/
public function adminCancelAccountMembership (
Request $request,
UserHelper $userHelper,
OrderHelper $orderHelper
) {
//Admin check
$access = false;
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$admin = $this->getUser();
if($admin) {
if($admin->isAdmin()) {
$access = true;
}
}
}
if(!$access) {
$this->addFlash("warning", "This page is only accessible to site administrators.");
return $this->redirectToRoute("/");
}
$user_id = $request->get("user_id");
$user = $userHelper->getUserById($user_id);
$manager = $this->getDoctrine()->getManager();
$item = $manager->getRepository(PurchaseItem::class)
->findOneBy([
"id" => $request->get("item_id"),
]);
$item->setStatus(PurchaseItem::STATUS_ACTIVE);
$manager->persist($item);
$manager->flush();
$this->addFlash("success", "Membership has been cancelled and will not auto-renew.");
return $this->redirectToRoute("admin-account-membership", [
"id" => $user_id,
]);
}
/**
* @Route("/admin-account/membership-continue", methods={"POST"}, name="post-admin-account-membership-continue")
*/
public function adminContinueAccountMembership (
Request $request,
UserHelper $userHelper,
OrderHelper $orderHelper
) {
//Admin check
$access = false;
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$admin = $this->getUser();
if($admin) {
if($admin->isAdmin()) {
$access = true;
}
}
}
if(!$access) {
$this->addFlash("warning", "This page is only accessible to site administrators.");
return $this->redirectToRoute("/");
}
$user_id = $request->get("user_id");
$user = $userHelper->getUserById($user_id);
$manager = $this->getDoctrine()->getManager();
$item = $manager->getRepository(PurchaseItem::class)
->findOneBy([
"id" => $request->get("item_id"),
]);
$item->setStatus($item->getPaymentFailed() ? PurchaseItem::STATUS_ACTIVE_RENEWING_FINAL : PurchaseItem::STATUS_ACTIVE_RENEWING);
$manager->persist($item);
$manager->flush();
$this->addFlash("success", "Membership has been re-activated and will now automatically renew.");
return $this->redirectToRoute("admin-account-membership", [
"id" => $user_id,
]);
}
/**
* @Route("/admin-account/membership-retry", methods={"POST"}, name="post-admin-account-membership-retry")
*/
public function adminRetryAccountMembership (
Request $request,
UserHelper $userHelper,
OrderHelper $orderHelper,
EmailHelper $emailHelper
) {
//Admin check
$access = false;
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$admin = $this->getUser();
if($admin) {
if($admin->isAdmin()) {
$access = true;
}
}
}
if(!$access) {
$this->addFlash("warning", "This page is only accessible to site administrators.");
return $this->redirectToRoute("/");
}
$user_id = $request->get("user_id");
$user = $userHelper->getUserById($user_id);
$entityManager = $this->getDoctrine()->getManager();
$item = $entityManager->getRepository(PurchaseItem::class)
->findOneBy([
"id" => $request->get("item_id"),
]);
/*
$item->setStatus($item->getPaymentFailed() ? PurchaseItem::STATUS_ACTIVE_RENEWING_FINAL : PurchaseItem::STATUS_ACTIVE_RENEWING);
$entityManager->persist($item);
$entityManager->flush();
*/
/* Modified copy of the OrderHelper's "updateExpiredPurchaseItems" function */
//TODO: move this to the OrderHelper so code isn't repeated
$currentStatus = PurchaseItem::STATUS_ACTIVE_RENEWING;
//Do this first: in case there's an error, it won't keep trying to renew
$item->setStatus(PurchaseItem::STATUS_INACTIVE);
//$item->setExpiresAt(null); //might be useful to see when it expired
$entityManager->persist($item);
$entityManager->flush();
$purchase_completed = false;
$product = $item->getProduct();
$purchase = $item->getPurchase();
if($purchase) {
$user = $purchase->getUser();
if($product && $user) {
if($user->getUserMetaValueByKey("has_payment_info")) {
$new_purchase = new Purchase();
$newItem = new PurchaseItem();
$newItem->setProduct($item->getProduct());
$newItem->setType($item->getType());
$newItem->setPurchase($new_purchase);
$new_purchase->setStatus(Purchase::STATUS_FAILED); //default to failed (we don't ever want it 'active')
$new_purchase->setCurrentItem($newItem);
$new_purchase->setUser($user);
$new_purchase->setDiscount(0);
//apply any coupons
$old_coupons = $purchase->getCoupons();
foreach($old_coupons as $coupon) {
if($coupon->getProductType() == $product->getType()
&& ($coupon->getRecurringType() == Coupon::RECURRING_UNLIMITED
|| ($coupon->getRecurringType() == Coupon::RECURRING_SET_MONTHS && $coupon->getMonthsRecurring() > $item->getMonthsRenewed()))
) {
$new_purchase->addCoupon($coupon);
}
}
//renew the purchase item
$result = $orderHelper->placeOrder(
$user->getUserMetaValueByKey("payment_first_name"),
$user->getUserMetaValueByKey("payment_last_name"),
$user->getUserMetaValueByKey("payment_company"),
$user->getUserMetaValueByKey("payment_address_line_1"),
$user->getUserMetaValueByKey("payment_address_line_2"),
$user->getUserMetaValueByKey("payment_city"),
$user->getUserMetaValueByKey("payment_state_province"),
$user->getUserMetaValueByKey("payment_postal_code"),
$user->getUserMetaValueByKey("payment_country"),
$user->getUserMetaValueByKey("payment_email"),
$user->getUserMetaValueByKey("payment_phone"),
"", //$_SERVER["REMOTE_ADDR"],
$new_purchase->getInvoiceNumber(),
$new_purchase->getTotalUsd(true),
$new_purchase->getTaxUsd(true),
"", //no card number
"", //no expiration date
"", //$user->getUserMetaValueByKey("payment_cvv2"),
false,
$user->getUserMetaValueByKey("payment_token")
);
$new_purchase->setFirstname($user->getUserMetaValueByKey("payment_first_name"));
$new_purchase->setLastname($user->getUserMetaValueByKey("payment_last_name"));
$new_purchase->setCompany($user->getUserMetaValueByKey("payment_company"));
$new_purchase->setAddressLine1($user->getUserMetaValueByKey("payment_address_line_1"));
$new_purchase->setAddressLine2($user->getUserMetaValueByKey("payment_address_line_2"));
$new_purchase->setCity($user->getUserMetaValueByKey("payment_city"));
$new_purchase->setStateProvince($user->getUserMetaValueByKey("payment_state_province"));
$new_purchase->setPostalCode($user->getUserMetaValueByKey("payment_postal_code"));
$new_purchase->setCountry($user->getUserMetaValueByKey("payment_country"));
$new_purchase->setEmail($user->getUserMetaValueByKey("payment_email"));
$new_purchase->setPhone($user->getUserMetaValueByKey("payment_phone"));
//$new_purchase->setLast4("");
//$new_purchase->setUserIP($_SERVER["REMOTE_ADDR"]);
//$new_purchase->setUserAgent($_SERVER["HTTP_USER_AGENT"]);
$new_purchase->setRawResponse(json_encode([
"body" => $result["raw"],
"request" => $result["request"],
]));
$purchaseNote = new PurchaseNote();
$purchaseNote->setAuthorName("RCS Payment Gateway");
$purchaseNote->setAuthorEmail("admin@rooferscoffeeshop.com");
if($result["result"] == "DECLINED 82") {
$result["result"] = "INVALID CAM\CVV";
}
if (/*true || */$result["result"] == "APPROVAL" || $result["result"] == "APPROVED") {
$purchaseNote->setDescription("Automatic payment attempt was successful. Response Code: {$result["code"]}. Response Message: {$result["result"]}");
$purchaseNote->setHiddenDescription(json_encode($result));
$new_purchase->addPurchaseNote($purchaseNote);
// mark purchase items as processed...
$new_purchase->setStatus(Purchase::STATUS_PROCESSED); //< this updates all expiration dates based on product purchased...
if($product->getPaymentRate() == Product::RENEW_YEARLY) {
$newItem->setMonthsRenewed($item->getMonthsRenewed() + 12);
}
else {
$newItem->setMonthsRenewed($item->getMonthsRenewed() + 1);
}
$purchase_completed = true;
}else{
$purchaseNote->setDescription("An error occurred while attempting to renew your purchase. Response Code: {$result["code"]}. Response Message: {$result["result"]}");
$purchaseNote->setHiddenDescription(json_encode($result));
$new_purchase->addPurchaseNote($purchaseNote);
// mark purchase items as failed...
$new_purchase->setStatus(Purchase::STATUS_FAILED); //< this updates all expiration dates based on product purchased...
}
$entityManager->persist($new_purchase);
$entityManager->flush();
}
else{
$purchaseNote = new PurchaseNote();
$purchaseNote->setAuthorName("RCS Payment Gateway");
$purchaseNote->setAuthorEmail("admin@rooferscoffeeshop.com");
$purchaseNote->setDescription("No Payment Information On Record.");
$purchase->addPurchaseNote($purchaseNote);
$purchase->setStatus(Purchase::STATUS_FAILED);
}
}
}
if($purchase_completed) {
//send purchase email
$message = [];
$message[] = ["p" => "Your R-Club membership has been successfully renewed for {$new_purchase->getTotalUsd()}."];
$message[] = ["a" => ["href" => "rooferscoffeeshop.com/account", "text" => "Go to your account page to update your membership settings at any time."]];
$this->addFlash("success", "Payment successful. Membership has been re-activated and will now automatically renew.");
return $this->redirectToRoute("admin-account-membership", [
"id" => $user_id,
]);
}
else {
$user->setMember(0);
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash("danger", "An error occurred when attempting to renew this user's membership. Response Code: {$result["code"]}. Response Message: {$result["result"]}");
return $this->redirectToRoute("admin-account-membership", [
"id" => $user_id,
]);
}
}
/**
* @Route("/admin-account/membership", methods={"POST"}, name="post-admin-account-membership")
*/
public function adminUpdateAccountMembership (
Request $request,
UserHelper $userHelper,
OrderHelper $orderHelper
) {
//Admin check
$access = false;
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$admin = $this->getUser();
if($admin) {
if($admin->isAdmin()) {
$access = true;
}
}
}
if(!$access) {
$this->addFlash("warning", "This page is only accessible to site administrators.");
return $this->redirectToRoute("/");
}
$user_id = $request->get("user_id");
$user = $userHelper->getUserById($user_id);
$payment = $request->get("payment");
$card = $request->get("card");
//expiration date
$card["card_expires"] = $card["card_expires_month"].$card["card_expires_year"];
if (!$payment || !isset($payment["terms"])) {
$this->addFlash("warning", "You must accept the terms and conditions.");
return $this->redirectToRoute("admin-account-membership", [
"id" => $user_id,
]);
}
$result = $orderHelper->generateToken(
$payment["firstname"],
$payment["lastname"],
$payment["company"],
$payment["address1"],
$payment["address2"],
$payment["city"],
$payment["state"],
$payment["zip"],
$payment["country"],
$payment["email"],
$payment["phone"],
$_SERVER["REMOTE_ADDR"],
$card["card_number"],
$card["card_expires"],
$card["card_csc"]
);
if ($result["result"] == "APPROVAL" || $result["result"] == "APPROVED") {
$last4 = $card["card_number"];
$last4 = preg_replace("/[^0-9]/", '', $last4);
$last4 = substr($last4, -4);
$user->setUsermetum("has_payment_info", "1");
$user->setUsermetum("payment_first_name", $payment["firstname"]);
$user->setUsermetum("payment_last_name", $payment["lastname"]);
$user->setUsermetum("payment_company", $payment["company"]);
$user->setUsermetum("payment_address_line_1", $payment["address1"]);
$user->setUsermetum("payment_address_line_2", $payment["address2"]);
$user->setUsermetum("payment_city", $payment["city"]);
$user->setUsermetum("payment_state_province", $payment["state"]);
$user->setUsermetum("payment_postal_code", $payment["zip"]);
$user->setUsermetum("payment_country", $payment["country"]);
$user->setUsermetum("payment_email", $payment["email"]);
$user->setUsermetum("payment_phone", $payment["phone"]);
$user->setUsermetum("payment_last4", $last4);
$user->setUsermetum("payment_exp", $card["card_expires"]);
//$user->setUsermetum("payment_cvv2", $card["card_csc"]);
$user->setUsermetum("payment_token", $result["token"]);
$user->setUsermetum("payment_token_response", $result["token_response"]);
$manager = $this->getDoctrine()->getManager();
$manager->persist($user);
$manager->flush();
$this->addFlash("success", "Membership settings updated.");
return $this->redirectToRoute("admin-account-membership", [
"id" => $user_id,
]);
}
else {
$this->addFlash("warning", "Their was an error while updating your payment information. Response: {$result["result"]}");
return $this->redirectToRoute("admin-account-membership", [
"id" => $user_id,
]);
}
}
}