src/Controller/RCS/ContentController.php line 205
<?php
namespace App\Controller\RCS;
use App\Controller\Master\ContentController as MasterContentController;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Form\Forms;
use App\Form\Type\ContentType;
use App\Form\Type\ContentAdminType;
use App\Form\Type\CommentType;
use App\Entity\Content;
use App\Entity\Site;
use App\Entity\SiteConfig;
use App\Entity\ContentMeta;
use App\Entity\Comment;
use App\Entity\Category;
use App\Entity\Customer;
use App\Entity\CustomerPhone;
use App\Entity\CustomerAddress;
use App\Entity\Lead;
use App\Entity\User;
use App\Entity\Coupon;
use App\Entity\Product;
use App\Entity\ProductOptionValue;
use App\Entity\Purchase;
use App\Entity\PurchaseItem;
use App\Entity\PurchaseNote;
use App\Entity\Media;
use App\Entity\MediaGroupItem;
use App\Entity\MediaGroup;
use App\Entity\MediaGroupContainer;
use App\Entity\Contact;
use App\Entity\ContentAnalyticsDaily;
use App\Entity\QuizQuestion;
use App\Form\Type\CustomerType;
use App\Form\Type\LeadType;
use App\Form\DirectoryLeadType;
use App\Utils\CategoryHelper;
use App\Utils\ContentHelper;
use App\Utils\CustomerHelper;
use App\Utils\ContactHelper;
use App\Utils\UserHelper;
use App\Utils\EmailHelper;
use App\Utils\OrderHelper;
use App\Utils\MediaHelper;
use App\Utils\MenuHelper;
use App\Utils\LeadHelper;
use App\Utils\PollHelper;
use Vich\UploaderBundle\Storage\StorageInterface;
use Vich\UploaderBundle\Mapping\PropertyMapping;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Twig\Environment;
class ContentController extends MasterContentController
{
public function contentMembersOnlyCheck($content) {
if($content->getMembersOnly() && (!$this->user || (!$this->user->isMember() && !$this->user->isAdmin()))) {
$this->addFlash("warning", "This page is only accessible to RCS Club members. Continue below to become a member and access this page.");
return $this->redirectToRoute("rcs-club-sign-up");
}
}
//Post override example:
/* *
* @ Route("/post/{slug}", name="post")
* /
public function post(
Request $request,
ContentHelper $contentHelper,
$slug = ""
) {
//return parent::post(func_get_args());
return parent::post($request, $contentHelper, $slug);
}*/
//TODO: Not normal route - called in template.
// displays the webinars list page
// requres a content object to be passed as $content
public function webinars(
Request $request,
ContentHelper $helper,
MediaHelper $mediaHelper,
$content = ""
) {
$webinars = [];
$webinars["coming_up"] = $helper->getContent(Content::WEBINAR, "coming-up-next", "published", "desc", 0, 0, false, "*", true)["content"];
$webinars["series_2018"] = $helper->getContent(Content::WEBINAR, "rcs-2018-webinar-series-on-demand", "published", "desc", 0, 0, false, "*", true)["content"];
$webinars["archive_marketing"] = $helper->getContent(Content::WEBINAR, "rcs-webinar-archive-contractor-marketing-series", "published", "desc", 0, 0, false, "*", true)["content"];
$webinars["archive_nrca"] = $helper->getContent(Content::WEBINAR, "rcs-webinar-archive-nrca-webinars", "published", "desc", 0, 0, false, "*", true)["content"];
$images = [];
foreach($webinars as $key => $value) {
$images[$key] = [];
foreach($value as $c) {
$cm = $c->getContentMetaByKey("webinar_showgraphic");
if(is_null($cm) || $cm->getMetavalue() == 0) {
$images[$key][] = "";
}
else {
$m = $mediaHelper->getMediaByOldId($cm->getMetavalue());
$images[$key][] = $m;
}
}
}
return $this->defaultRender("content/tmpl/webinars.html.twig", [
"content" => $content,
"webinars" => $webinars,
"images" => $images,
"meta" => [
"adGroup" => 'rlw'
]
]);
}
// displays the partner webinars page
// requres a content object to be passed as $content
public function partnerwebinars(
Request $request,
ContentHelper $helper,
MediaHelper $mediaHelper,
$content = ""
) {
$webinars = [];
$webinars["coming_up"] = $helper->getContent(Content::WEBINAR, "partner-coming-up-next", "published", "desc", 0, 0, false, "*", true)["content"];
//$webinars["on_demand"] = $helper->getContent(Content::WEBINAR, "partner-on-demand", "published", "desc", 0, 0, false, "*", true)["content"];
return $this->defaultRender("content/tmpl/partner-webinars.html.twig", [
"content" => $content,
"webinars" => $webinars,
]);
}
//TODO: test
// displays the roofing galleries page
// requres a content object to be passed as $content
public function roofinggalleries(
Request $request,
ContentHelper $helper,
MediaHelper $mediaHelper,
$content = ""
) {
//$galleries = [];
//$galleries = $helper->getContentByType(Content::GALLERY, 'title');
$galleries = $helper->getGalleries("roofing-galleries", "title");
/*
//$galleries[] = $helper->getContentBySlug(Content::GALLERY, "a-day-in-the-life");
$galleries[] = $helper->getContentBySlug(Content::GALLERY, "beautiful-roofing");
$galleries[] = $helper->getContentBySlug(Content::GALLERY, "craftsmanship");
$galleries[] = $helper->getContentBySlug(Content::GALLERY, "fun-photos");
$galleries[] = $helper->getContentBySlug(Content::GALLERY, "green-roofs");
$galleries[] = $helper->getContentBySlug(Content::GALLERY, "metal-roofing");
$galleries[] = $helper->getContentBySlug(Content::GALLERY, "roof-of-the-month");
$galleries[] = $helper->getContentBySlug(Content::GALLERY, "roofers-in-action");
$galleries[] = $helper->getContentBySlug(Content::GALLERY, "roofing-history");
$galleries[] = $helper->getContentBySlug(Content::GALLERY, "solar-roofing");
$galleries[] = $helper->getContentBySlug(Content::GALLERY, "unique-roofs");
$galleries[] = $helper->getContentBySlug(Content::GALLERY, "what-happened-here");
*/
return $this->defaultRender("content/tmpl/roofing-galleries.html.twig", [
"content" => $content,
"galleries" => $galleries,
]);
}
// displays the partner galleries page
// requres a content object to be passed as $content
public function partnergalleries(
Request $request,
ContentHelper $helper,
MediaHelper $mediaHelper,
$content = ""
) {
$galleries = $helper->getGalleries("partner-galleries", "title");
return $this->defaultRender("content/tmpl/roofing-galleries.html.twig", [
"content" => $content,
"galleries" => $galleries,
]);
}
// displays the meet the Zoom embed page
// requres a content object to be passed as $content
public function zoomembed(
Request $request,
ContentHelper $helper,
$content = ""
) {
/*
$chatAccess = false;
$ssoParams = "";
$moderator = 0;
$name = "Guest";
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$user = $this->getUser();
if($user) {
$chatAccess = true;
if($user->isAdmin()) {
$moderator = 1;
}
// Chatroll Single Sign-On (SSO) Parameters
$uid = $user->getId(); // Current user id
$uname = $user->getUsername(); // Current user name
$ulink = ''; // Current user profile URL (leave blank for none)
$upic = ''; // Current user profile picture URL (leave blank for none)
//if($user->getMedia()) {
// $upic = $user->getMedia()->getAbsoluteURL();
//}
$ismod = $moderator; // Is current user a moderator?
$sig = md5($uid . $uname . $ismod . 'b7ofqalwup2rtbkg');
$ssoParams = '&uid=' . $uid . "&uname=" . urlencode($uname) . "&ulink=" . urlencode($ulink) . "&upic=" . urlencode($upic) . "&ismod=" . $ismod . "&sig=" . $sig;
}
}
*/
$meetingAccess = false;
$name = "Guest";
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$user = $this->getUser();
if($user) {
$name = $user->getDisplayname();
$meetingAccess = true;
}
}
$name = base64_encode($name);
$meetingId = str_replace("-", "", $content->getZoomMeetingId());
$displayMeeting = $content->getZoomDisplayMeeting();
return $this->defaultRender("content/tmpl/zoom-embed.html.twig", [
//"chatAccess" => $chatAccess,
//"ssoParams" => $ssoParams,
"content" => $content,
"meetingId" => $meetingId,
"displayMeeting" => $displayMeeting,
"name" => $name,
"meetingAccess" => $meetingAccess,
]);
}
//TODO: landing pages
/**
* @Route("/rcs/{slug}", name="submit-landing-page", methods={"POST"})
*
*/
public function submitLandingPage (
ContentHelper $contentHelper,
EmailHelper $emailHelper,
LeadHelper $leadHelper,
Request $request,
Container $container,
$slug
) {
if($emailHelper->checkCaptcha($request->get("g-recaptcha-response"))) {
// because of time constraints - processing here
$lead = $request->get("lead");
if(!$lead) {$lead = [];}
$firstname = array_key_exists("firstname", $lead) ? $lead["firstname"] : "";
$lastname = array_key_exists("lastname", $lead) ? $lead["lastname"] : "";
$company = array_key_exists("company", $lead) ? $lead["company"] : "";
$phone = array_key_exists("phone", $lead) ? $lead["phone"] : "";
$email = array_key_exists("email", $lead) ? $lead["email"] : "";
$contractor_type = array_key_exists("contractor_type", $lead) ? $lead["contractor_type"] : "";
$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"] : "";
//special form fields (until the form builder is made):
// *Note: also need to add to Utils/LeadHelper
$collar_size = array_key_exists("collar_size", $lead) ? $lead["collar_size"] : "";
$years_in_business = array_key_exists("years_in_business", $lead) ? $lead["years_in_business"] : "";
$num_field_crew = array_key_exists("num_field_crew", $lead) ? $lead["num_field_crew"] : "";
$annual_revenue = array_key_exists("annual_revenue", $lead) ? $lead["annual_revenue"] : "";
$self_perform_trade = array_key_exists("self_perform_trade", $lead) ? $lead["self_perform_trade"] : "";
//custom fields from the form builder
$lead_custom = $request->get("lead_custom");
$lead_custom_img = $request->get("lead_custom_img");
$lead_custom_file = $request->get("lead_custom_file");
try {
$content = $contentHelper->getLandingPageBySlug($slug);
if(!empty($content->getContentMetaByKey("lp_recipients"))) {
$recipients = explode(",", $content->getContentMetaByKey("lp_recipients")->getMetavalue());
}
else {
$recipients = array();
}
$thankyou = $content->getContentMetaValueByKey("lp_thankyou");
$titles = array();
$lead_info = [];
if($firstname) {$lead_info["First Name"] = $firstname;}
if($lastname) {$lead_info["Last Name"] = $lastname;}
if($company) {$lead_info["Company"] = $company;}
if($phone) {$lead_info["Phone Number"] = $phone;}
if($email) {$lead_info["Email Address"] = $email;}
if($address1) {$lead_info["Address Line 1"] = $address1;}
if($address2) {$lead_info["Address Line 2"] = $address2;}
if($city) {$lead_info["City"] = $city;}
if($state) {$lead_info["State / Region"] = $state;}
if($zip) {$lead_info["Zip Code"] = $zip;}
if($contractor_type) {$lead_info["Contractor Type"] = $contractor_type;}
//special form fields
$special_fields = [];
if($collar_size) {
$lead_info["Collar Size"] = $collar_size;
$special_fields["collar_size"] = $collar_size;
}
if($years_in_business) {
$lead_info["Years in Business"] = $years_in_business;
$special_fields["years_in_business"] = $years_in_business;
}
if($num_field_crew) {
$lead_info["Approximate Number of Field Crew"] = $num_field_crew;
$special_fields["num_field_crew"] = $num_field_crew;
}
if($annual_revenue) {
$lead_info["Annual Revenue"] = $annual_revenue;
$special_fields["annual_revenue"] = $annual_revenue;
}
if($self_perform_trade) {
$lead_info["Self-Perform Trade"] = $self_perform_trade;
$special_fields["self_perform_trade"] = $self_perform_trade;
}
if($lead_custom) {
foreach($lead_custom as $key => $value) {
if(is_array($value)) {
//Set the checkbox value to all selected values
$lead_custom[$key] = implode(", ", $value);
}
if(!$email && strtolower($key) == "email") {
$email = $value;
}
}
$lead_info = array_merge($lead_info, $lead_custom);
}
if($email && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->addFlash("danger", "The provided e-mail address is invalid.");
return new RedirectResponse($request->headers->get('referer'));
}
//Handle images separately, so they won't be emailed the ids
$lead_custom_files = [];
$uploaded_media = [];
if($lead_custom_img) {
foreach($lead_custom_img as $key => $value) {
if ($request->files->get("img_".$key)) { //image field
$uploaded_image = $request->files->get("img_".$key);
$mime = $uploaded_image->getMimeType();
if(!in_array($mime, ["image/jpg", "image/jpeg", "image/png", "image/gif", "application/pdf"])) {
$this->addFlash("danger", "Only PNG, JPG, GIF, and PDF file types are allowed.");
return new RedirectResponse($request->headers->get('referer'));
}
/*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'));
}*/
$media = new Media();
$media->setTitle(pathinfo($uploaded_image->getClientOriginalName(), PATHINFO_FILENAME));
$media->setData($uploaded_image);
$media->setDescription("Lead image - LP " . $content->getId() . " - " . $key);
$media->setName($uploaded_image->getClientOriginalName());
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($media);
$entityManager->flush();
$lead_custom_files[$value] = $media->getId();
unset($lead_custom_img[$key]);
//$lead_custom_img[$value] = $lead["img_".$key];
$uploaded_media[] = $media;
}
}
//$lead_info = array_merge($lead_info, $lead_custom_img);
//$lead_custom = array_merge($lead_custom, $lead_custom_images);
}
if($lead_custom_file) {
foreach($lead_custom_file as $key => $value) {
if ($request->files->get("file_".$key)) {
$uploaded_file = $request->files->get("file_".$key);
$media = new Media();
$media->setTitle(pathinfo($uploaded_file->getClientOriginalName(), PATHINFO_FILENAME));
$media->setData($uploaded_file);
$media->setDescription("Lead file - LP " . $content->getId() . " - " . $key);
$media->setName($uploaded_file->getClientOriginalName());
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($media);
$entityManager->flush();
$lead_custom_files[$value] = $media->getId();
unset($lead_custom_file[$key]);
$uploaded_media[] = $media;
}
}
//$lead_info = array_merge($lead_info, $lead_custom_file);
//$lead_custom = array_merge($lead_custom, $lead_custom_images);
}
/*
//Uncomment if we want leads from landing pages to go to Customer emails instead of just lp_recipients
$customers = $content->getCustomers();
for ($i = 0; $i < count($customers); $i++) {
$customer = $customers[$i];
$title = $customer->getTitle();
$titles[] = $title;
if (filter_var($customer->getEmail(), FILTER_VALIDATE_EMAIL)) {
$recipient = $customer->getEmail();
if (in_array($recipient, $recipients)) {
unset($recipients[array_search($recipient, $recipients)]);
}
$emailHelper->sendEmail(
[$recipient],
"Lead Received - {$title}",
[
["p" => "Lead received for {$title}"],
["table" => [
"Firstname" => $firstname,
"Lastname" => $lastname,
"Company" => $company,
"Phone Number" => $phone,
"Email Address" => $email,
"Contractor Type" => $contractor_type,
//"Recipient (customer)" => $recipient,
]],
]
);
}
}
*/
$titles = implode(",", $titles);
//using the landing page title instead of customer names:
$title = $content->getTitle();
if(!empty($recipients)) {
$user_text = "";
if ($this->user) {
$user_text = " from user <strong>" . $this->user->getUsername() . "</strong>";
}
$emailHelper->sendEmail(
$recipients,
"Lead Received - {$title}",
[
["p" => "Lead received for <strong>{$title}</strong>{$user_text}"],
["table" => $lead_info ],
], [], "", "", "", $uploaded_media //if images
);
}
// store the lead
$leadHelper->saveLead($lead, $content, $request, $lead_custom, $lead_custom_files);
/*
$lead = new Lead();
$lead->setFirstname($firstname);
$lead->setLastname($lastname);
$lead->setCompany($company);
$lead->setPhoneBusiness($phone);
$lead->setEmail($email);
$lead->setTypeBusiness($contractor_type);
$lead->setAddress1($address1);
$lead->setAddress2($address2);
$lead->setCity($city);
$lead->setState($state);
$lead->setZip($zip);
//special form fields
if(!empty($special_fields)) {
$lead->setComments(json_encode($special_fields));
}
$lead->setIpAddress($request->getClientIp());
$lead->setRefUrl($request->headers->get("referer"));
$lead->setUserAgent($request->headers->get("User-Agent"));
$lead->setContent($content);
$em = $this->getDoctrine()->getManager();
$em->persist($lead);
$em->flush();
*/
/*
$redirect = substr($thankyou, strpos($thankyou, '?gaplg=') + 7);
if(!$redirect) {
$redirect = substr($thankyou, strpos($thankyou, '.com/') + 5);
}
*/
//return $this->redirect("/" . strstr($thankyou, "?gaplg="));
//2-28-2019 changing to just a straight redirect
//$redirect = substr($thankyou, strpos($thankyou, '.com/') + 5);
//return $this->redirect("/" . $redirect);
$thankyouUrl = "https://rooferscoffeeshop.com";
$env = $container->getParameter('kernel.environment');
if($env == "dev") {
$thankyouUrl = "https://staging.rooferscoffeeshop.com";
}
if($thankyou) {
$thankyouUrl = $thankyou;
}
else {
$children = $content->getChildren();
if(!$children->isEmpty()) {
$thanks = $children->first();
if($thanks->getContentFull()) {
if($env == "dev") {
$thankyouUrl = "https://staging.rooferscoffeeshop.com" . $thanks->getURL();
}
else {
$thankyouUrl = "https://rooferscoffeeshop.com" . $thanks->getURL();
}
}
}
}
if($content->getLPEmailSend()) {
if($email && filter_var($email, FILTER_VALIDATE_EMAIL)) {
$defaultBody = "Thank you for your interest in: {$title}.";
//Send custom email to the user (if valid email was entered)
$emailHelper->sendEmail(
$email,
"Form Completed - {$title}",
[
["p" => $content->getLPEmailContents() ? $content->getLPEmailContentsImgFix() : $defaultBody ],
//["p" => "Email Recipient: {$email}" ],
/*["a" => [
"href" => "{$thankyouUrl}",
"text" => $content->getLPEmailButtonText() ? $content->getLPEmailButtonText() : "Click Here to view."]
],*/
],
[],
"",
""
);
}
// Need to also handle $lead_custom
}
//Redirect to the thank you page
if($thankyouUrl) {
return $this->redirect($thankyouUrl);
}
else {
return $this->redirect("/");
}
//return $this->redirect($thankyou ? $thankyou : "/");
/*
return $this->defaultRender("content/landing-page.html.twig", [
"page" => $content,
"message" => [
"type" => "success",
"text" => "Form submitted successfully.",
]
]);
*/
}
catch (ResourceNotFoundException $e) {
}
}
else {
//Flash messages not showing up on landing pages, need to update this
//$this->addFlash("danger", "The reCAPTCHA was invalid. Please try again.");
return new RedirectResponse($request->headers->get('referer'));
}
}
/**
* @Route("/rcs/{slug}", name="landing-page")
*
*/
public function showLandingPage (
ContentHelper $contentHelper,
Request $request,
$slug
) {
try {
//Handle the unique RCS'ers questions page.
if($slug == "rcsers-questions") {
if (!$this->user) {
$msg = [
"type" => "warning",
"text" => "Please sign in to view this page.",
];
return $this->redirectToRoute("sign-in", [
"message" => $msg
]);
}
}
$page = $contentHelper->getLandingPageBySlug($slug);
return $this->defaultRender("content/landing-page.html.twig", [
"page" => $page,
"meta" => [
"title" => $page->getTitle(),
],
]);
}
catch (ResourceNotFoundException $e) {
}
return $this->defaultRender("errors/404.html.twig", [
]);
}
//TODO
/**
* @Route("/download-report", name="download_report")
**/
public function downloadReportAction(
Request $request,
ContentHelper $helper
){
//$filename = "Analytics RoofersCoffeeShop.com - CertainTeed Corporation - March-2019.xlsx";
$filename = $request->request->get("filename");
$response = new BinaryFileResponse("../var/reports/{$filename}");
//$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT,'pdf.pdf');
$pos = strrpos($filename, '/');
$filename = $pos === false ? $filename : substr($filename, $pos + 1);
$disposition = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
$filename
);
$response->headers->set('Content-Disposition', $disposition);
return $response;
}
//TODO
/**
* @Route("/admin_mega_menu"),
* name="admin_mega_menu"
*/
public function menuBuilderDashboard(
Request $request,
ContentHelper $contentHelper
){
$access = false;
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$user = $this->getUser();
if($user) {
if($user->isSuperAdmin()) {
$access = true;
}
}
}
return $this->defaultRender("admin/mega_menu_builder.html.twig", [
"access" => $access,
"meta" => [
"title" => "Mega Menu Builder",
"root" => "/",
]
]);
}
//TODO: new controllers for this and tax report
/**
* @Route(
* "/admin-dashboard",
* name="admin_dashboard"
* )
*/
public function loadingAdminDashboard(
Request $request,
ContentHelper $contentHelper
) {
set_time_limit(180);
$access = false;
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$user = $this->getUser();
if($user) {
if($user->isAdmin()) {
$access = true;
}
}
}
return $this->defaultRender("content/loading-admin-dashboard.html.twig", [
"access" => $access,
"meta" => [
"title" => "Admin Dashboard",
"root" => "/admin-directory",
]
]);
}
/**
* @Route("/ajax/admin-dashboard")
*/
public function adminDashboardEmbed(
Request $request,
ContentHelper $contentHelper,
CustomerHelper $customerHelper,
CategoryHelper $categoryHelper,
MediaHelper $mediaHelper,
MenuHelper $menuHelper,
Environment $twig
) {
try {
set_time_limit(180);
$entityManager = $this->getDoctrine()->getManager();
$currentYear = date("Y");
$month = date("n");
if($request->request->has("year")) {
$year = $request->request->get("year");
if($year < $currentYear) {
$month = 12;
}
}
else {
$year = $currentYear;
//Only show up for this year if after January
if($month == 1) {
$year = $currentYear - 1;
//$currentYear = $year;
$month = 12;
}
}
$customers = $customerHelper->getActiveCustomers();
$rows = [];
$keys = [];
foreach($customers as $customer) {
$c_info = [];
$c_info["Customer"] = htmlspecialchars_decode($customer->getTitle());
$c_info["Partner Level"] = htmlspecialchars_decode($customer->getCustomerLevelString());
$c_info["Directory Type"] = htmlspecialchars_decode($customer->getCustomerTypeString());
for($m = 1; $m <= $month; $m++) {
$dateObj = \DateTime::createFromFormat('!m', $m);
$monthName = $dateObj->format('M');
if($year == $currentYear && $month == $m) {
//don't want the current month; only months with complete data
break;
//$monthName = "(partial) ".$monthName;
}
$startDate = date("Y-m-d", strtotime($year."-".$m."-"."01"));
$startDate = new \DateTime($startDate);
$endDate = date("Y-m-t", strtotime($year."-".$m."-"."01"));
$endDate = new \DateTime($endDate." 23:59:59");
$monthly_impressions = $customer->getMonthlyImpressions($year, $m);
$monthly_clicks = $customer->getMonthlyClicks($year, $m);
$monthly_views = $customer->getMonthlyViews($year, $m);
if($monthly_impressions !== false && $monthly_clicks !== false && $monthly_views !== false) {
$c_info[$monthName . " Total Impressions"] = $monthly_impressions;
$c_info[$monthName . " Total Page Views"] = $monthly_views;
$c_info[$monthName . " Total Clicks"] = $monthly_clicks;
}
else {
$links = $contentHelper->countContentLinkClicks($customer, $startDate, $endDate);
$total_link_clicks = 0;
foreach($links as $key => $value) {
$total_link_clicks += $links[$key]["count"] ? $links[$key]["count"] : 0;
}
$total_content_impressions = $contentHelper->countCustomerContentImpressionsAggregatedCorrected($customer, $startDate, $endDate);
$total_content_views = $contentHelper->countCustomerContentClicksAggregated($customer, $startDate, $endDate);
$total_ad_impressions = $mediaHelper->countTotalAdImpressionsAggregated($customer, $startDate, $endDate);
$total_ad_clicks = $mediaHelper->countTotalAdClicksAggregated($customer, $startDate, $endDate);
$monthly_impressions = $total_content_impressions + $total_ad_impressions;
$monthly_clicks = $total_link_clicks + $total_ad_clicks;
$monthly_views = $total_content_views;
$c_info[$monthName . " Total Impressions"] = $monthly_impressions;
$c_info[$monthName . " Total Page Views"] = $monthly_views;
$c_info[$monthName . " Total Clicks"] = $monthly_clicks;
$customer->setMonthlyImpressions($year, $m, $monthly_impressions);
$customer->setMonthlyClicks($year, $m, $monthly_clicks);
$customer->setMonthlyViews($year, $m, $monthly_views);
$entityManager->persist($customer);
$entityManager->flush();
}
}
$rows[] = $c_info;
$keys = array_keys($c_info);
}
//Export / Spreadsheet
$spreadsheet = new Spreadsheet();
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet_title = "RCS Customer Monthly Review ".date_format(new \DateTime(), 'M Y');
$colVal = "A";
$rowNum = 1;
foreach($keys as $key) {
$sheet->setCellValue("{$colVal}{$rowNum}", $key);
$colVal++;
}
$colVal--;
$sheet->getStyle("A{$rowNum}:{$colVal}{$rowNum}")->getFill()
->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
->getStartColor()->setARGB('FFDDDDDD');
$rowNum++;
foreach($rows as $row) {
$colVal = "A";
foreach($row as $key => $value) {
$sheet->setCellValue("{$colVal}{$rowNum}", $value);
$colVal++;
}
$rowNum++;
}
$colVal--;
foreach(range("A",$sheet->getHighestColumn()) as $columnID) {
$sheet->getColumnDimension($columnID)
->setAutoSize(true);
}
//Finish and save
$writer = new Xlsx($spreadsheet);
$clean_title = preg_replace('/[^A-Za-z0-9 \-_]/', '', $sheet_title); // Removes special chars.
$filename = "{$clean_title}.xlsx";
$writer->save("../var/reports/{$filename}");
// End Export / Spreadsheet
$tmpl = $twig->load("content/admin-dashboard-embed.html.twig");
$html = $tmpl->render(
[
"rows" => $rows,
"keys" => $keys,
"filename" => $filename,
"currentYear" => $currentYear,
"year" => $year,
]);
return new JsonResponse($html);
} catch (\Exception $e) {
return new JsonResponse("<br><h4 style='text-align: center; color: #A7252B;'>There was an error while generating your report.</h4>");
//throw $e;
}
}
/**
* @Route(
* "/tax-report",
* name="tax_report"
* )
*/
public function loadingTaxReport(
Request $request,
ContentHelper $contentHelper
) {
set_time_limit(180);
$access = false;
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$user = $this->getUser();
if($user) {
if($user->isAdmin()) {
$access = true;
}
}
}
return $this->defaultRender("content/loading-tax-report.html.twig", [
"access" => $access,
"meta" => [
"title" => "Tax Report",
"root" => "/tax-report",
]
]);
}
/**
* @Route("/ajax/tax-report")
*/
public function taxReportEmbed(
Request $request,
OrderHelper $orderHelper,
Environment $twig
) {
try {
set_time_limit(180);
/*
//Update to allow year selection
if($request->request->has("year") && $request->request->get("year")) {
$year = date("Y", strtotime($request->request->get("year")));
}
$year = 2020;
*/
$year = date("Y");
$month = date("n");
$rows = [];
for($m = 1; $m <= $month; $m++) {
$startDate = date("Y-m-d", strtotime($year."-".$m."-"."01"));
$startDate = new \DateTime($startDate);
$endDate = date("Y-m-t", strtotime($year."-".$m."-"."01"));
$endDate = new \DateTime($endDate." 23:59:59");
$sales = $orderHelper->sumPurchaseTotalsByType(Product::PRODUCT_TYPE_SHOP, $startDate, $endDate);
$tax = $orderHelper->sumTaxes($startDate, $endDate);
$dateObj = \DateTime::createFromFormat('!m', $m);
$monthName = $dateObj->format('F');
if($month == $m) {
$monthName = $monthName." (partial)";
}
//$rows[$monthName] = $results;
$rows[] = [
"month" => $monthName,
"sales" => '$' . number_format($sales / 100, 2),
"tax" => '$' . number_format($tax / 100, 2),
];
}
$tmpl = $twig->load("content/tax-report-embed.html.twig");
$html = $tmpl->render(
[
"year" => $year,
"rows" => $rows,
]);
return new JsonResponse($html);
} catch (\Exception $e) {
//return new JsonResponse("<br><h4 style='text-align: center; color: #A7252B;'>There was an error while generating your report.</h4>");
throw $e;
}
}
//TODO: Keeping forum routes here for now. See if we can modify and use master functions.
/**
* @Route("/forum", name="forums")
*/
public function forums(
Request $request,
ContentHelper $helper,
$slug = ""
) {
$forums = array();
foreach($helper->getContentByType(Content::FORUM) as $forum) {
$counts = $helper->countTopicsPostsByForum($forum->getSlug());
$topics = $helper->getTopicsByForum($forum, 1, 1);
$topic = "";
foreach($topics as $t) {
$topic = $t;
}
$featured = $forum->getFeatured();
$forums[] = [
"forum" => $forum,
"num_topics" => $counts["num_topics"],
"num_posts" => $counts["num_posts"],
"recent_topic" => $topic,
"featured" => $featured,
];
}
$num_topics = array();
foreach($forums as $key => $row) {
$num_topics[$key] = $row["num_topics"] + ($row["featured"] * 100000);
}
array_multisort($num_topics, SORT_DESC, $forums);
$chatAccess = false;
$ssoParams = "";
$moderator = 0;
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$user = $this->getUser();
if($user) {
$chatAccess = true;
if($user->isAdmin() /*|| $user->inCompany($customer)*/) {
$moderator = 1;
}
// Chatroll Single Sign-On (SSO) Parameters
$uid = $user->getId(); // Current user id
$uname = $user->getUsername(); // Current user name
$ulink = ''; // Current user profile URL (leave blank for none)
$upic = ''; // Current user profile picture URL (leave blank for none)
/*if($user->getMedia()) {
$upic = $user->getMedia()->getAbsoluteURL();
}*/
$ismod = $moderator; // Is current user a moderator?
$sig = md5($uid . $uname . $ismod . 'b7ofqalwup2rtbkg');
$ssoParams = '&uid=' . $uid . "&uname=" . urlencode($uname) . "&ulink=" . urlencode($ulink) . "&upic=" . urlencode($upic) . "&ismod=" . $ismod . "&sig=" . $sig;
}
}
return $this->defaultRender("content/forums-page.html.twig", [
"meta" => [
"title" => "Forums Archive",
"breadcrumbs" => [
[
"title" => "Our Forums",
"href" => "/forum",
]
]
],
"forums" => $forums,
"chatAccess" => $chatAccess,
"ssoParams" => $ssoParams,
]);
}
/**
* @Route("/forum/topic/{slug}/edit", name="forum_topic_edit")
*/
public function forumTopicEdit(
Request $request,
ContentHelper $helper,
$slug = ""
) {
$topic = $helper->getTopicBySlug($slug);
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$user = $this->getUser();
if($user) {
//$unrestricted = $user->getUserMetaValueByKey("rich_editing");
if($user->isAdmin()) {
//fully edit topic
if ($request->request->has("content")) {
$topic->setTitle($request->request->get("title"));
$topic->setContentFull($request->request->get("content"));
$topic->setPrnt($helper->getContentById($request->request->get("forum")));
$topic->setStatus($request->request->get("status"));
$em = $this->getDoctrine()->getManager();
$em->persist($topic);
$em->flush();
$this->addFlash("success", "Topic has been updated.");
return $this->redirectToRoute("forum_topic", ["slug" => $topic->getSlug(), "page" => "1"]);
}
return $this->defaultRender("content/tmpl/forum-topic-edit.html.twig", [
"content" => $topic,
//"unrestricted" => isset($unrestricted) ? $unrestricted : "",
"unrestricted" => true,
"forums" => $helper->getContentByType(Content::FORUM),
"admin" => true,
]);
}
elseif($topic->getAuthor() == $user) {
//just allow them to edit the content and title
if ($request->request->has("content")) {
$topic->setTitle($request->request->get("title"));
$topic->setContentFull($request->request->get("content"));
$em = $this->getDoctrine()->getManager();
$em->persist($topic);
$em->flush();
$this->addFlash("success", "Topic has been updated.");
return $this->redirectToRoute("forum_topic", ["slug" => $topic->getSlug(), "page" => "1"]);
}
return $this->defaultRender("content/tmpl/forum-topic-edit.html.twig", [
"content" => $topic,
//"unrestricted" => isset($unrestricted) ? $unrestricted : "",
"unrestricted" => true,
"admin" => false,
]);
}
}
}
return $this->redirectToRoute("forum_topic", ["slug" => $topic->getSlug(), "page" => "1"]);
}
/**
* @Route("/forum/topic/{slug}/delete", name="forum_topic_delete")
*/
public function forumTopicDelete(
Request $request,
ContentHelper $helper,
$slug = ""
) {
$topic = $helper->getTopicBySlug($slug);
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$user = $this->getUser();
if($user) {
if($user->isAdmin()) {
$topic->setStatus(Content::STATUS_INACTIVE);
$em = $this->getDoctrine()->getManager();
$em->persist($topic);
$em->flush();
foreach($topic->getChildren() as $child) {
$child->setStatus(Content::STATUS_INACTIVE);
$em->persist($child);
$em->flush();
}
$this->addFlash("success", "Topic has been deleted.");
return $this->redirectToRoute("forum", ["slug" => $topic->getPrnt()->getSlug(), "page" => "1"]);
}
}
}
}
/**
* @Route("/forum/topic/{slug}/unsubscribe/{userid}", name="forum_topic_unsubscribe")
*/
public function forumTopicUnsubscribe(
Request $request,
ContentHelper $helper,
UserHelper $userhelper,
$slug = "",
$userid = ""
) {
$topic = $helper->getTopicBySlug($slug);
$user = $userhelper->getUserById($userid);
$entityManager = $this->getDoctrine()->getManager();
if($topic->getAuthor() == $user) {
$topic->setContentmetum("_notify_of_replies", "0");
$entityManager->persist($topic);
$entityManager->flush();
}
foreach($topic->getActiveChildren() as $reply) {
if($reply->getAuthor() == $user) {
$reply->setContentmetum("_notify_of_replies", "0");
$entityManager->persist($reply);
$entityManager->flush();
}
}
$this->addFlash("success", "You will no longer receive email notifications about the \"{$topic->getTitle()}\" forum topic.");
return $this->redirectToRoute("forum", ["slug" => $topic->getPrnt()->getSlug(), "page" => "1"]);
}
/**
* @Route("/forum/topic/{slug}/spam", name="forum_topic_spam")
*/
public function forumTopicSpam(
Request $request,
ContentHelper $helper,
$slug = ""
) {
$topic = $helper->getTopicBySlug($slug);
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$user = $this->getUser();
if($user) {
if($user->isAdmin()) {
$forumUser = $topic->getAuthor();
if($forumUser) {
$forumUser->markAsSpam();
$em = $this->getDoctrine()->getManager();
$em->persist($forumUser);
$em->flush();
/* //Should we do this?
foreach($topic->getChildren() as $child) {
$child->setStatus(Content::STATUS_INACTIVE);
$em->persist($child);
$em->flush();
}
*/
$this->addFlash("success", "User has been marked as spam.");
}
else {
$this->addFlash("warning", "There was a problem marking this user as spam.");
}
return $this->redirectToRoute("forum", ["slug" => $topic->getPrnt()->getSlug(), "page" => "1"]);
}
}
}
}
/**
* @Route("/forum/topic/{slug}/{page}", name="forum_topic")
*/
public function forumTopic(
Request $request,
ContentHelper $helper,
EmailHelper $emailHelper,
$slug = "",
$page = 1
) {
$topic = $helper->getTopicBySlug($slug);
$limit = ContentHelper::FORUM_LIMIT;
$forum = $topic->getPrnt();
if($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
/*
if(isset($unrestricted) && $unrestricted) {
$form = $this->createForm(ContentAdminType::class, $content);
}
else {
$form = $this->createForm(ContentType::class, $content);
}
$form->handleRequest($request);
*/
//if ($form->isSubmitted() && $form->isValid()) {
if ($request->request->has("reply-content")) {
$content = new Content();
$entityManager = $this->getDoctrine()->getManager();
$site = $entityManager
->getRepository(Site::class)
->findOneBy([
"id" => $this->site_code
]);
$content->addSite($site);
$content->setType(Content::FORUM_REPLY);
$content->setPrnt($topic);
$content->setPermission(1);
$user = $this->getUser();
if($user) {
$content->setAuthor($user);
//$unrestricted = $user->getUserMetaValueByKey("rich_editing");
}
if($emailHelper->checkInvisibleCaptcha($request->get("g-recaptcha-response"))) {
$notify = new ContentMeta();
$notify->setMetakey("_notify_of_replies");
$request->request->has("notify") ? $notify->setMetavalue(1) : $notify->setMetavalue(0);
$content->addContentmetum($notify);
$content_full = $request->request->get("reply-content");
if(!$this->user->isAdmin()) {
$content_full = preg_replace('/<a[^>]+>([^<]+)<\/a>/i','\1',$content_full);
}
$content->setContentFull($content_full);
if($helper->isSpam($request->request->get("reply-content"))) {
$content->setStatus(Content::STATUS_IN_REVIEW);
}
else {
$content->setStatus(Content::STATUS_ACTIVE);
}
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($content);
$entityManager->flush();
$this->addFlash("success", "Your reply has been added.");
if($topic->getContentMetaValueByKey("_notify_of_replies")) {
//forum_email
$pooled = $emailHelper->sendEmail($topic->getAuthor()->getEmail(), "New Reply to one of your Forum Topics", [
["p" => "Hello {$topic->getAuthor()},"],
["p" => "{$content->getAuthor()} has replied to your forum topic <a href=\"{$topic->getFullURL()}\">\"{$topic->getTitle()}\"</a> with the following reply:"],
["p" => "{$content->getContentFull()}"],
//["a" => ["href" => "staging.rooferscoffeeshop.com/forum/topic/{$topic->getSlug()}/unsubscribe/{$topic->getAuthor()->getId()}", "text" => "Click Here to stop receiving these notifications"]],
["a" => ["href" => "rooferscoffeeshop.com/forum/topic/{$topic->getSlug()}/unsubscribe/{$topic->getAuthor()->getId()}", "text" => "Click Here to stop receiving these notifications"]],
], [], "", "lauren@rooferscoffeeshop.com");
}
$notify_users = array();
foreach($topic->getActiveChildren() as $reply) {
if($reply != $content) {
if($reply->getContentMetaValueByKey("_notify_of_replies") && !in_array($reply->getAuthor(), $notify_users)
&& $reply->getAuthor() != $topic->getAuthor() && $reply->getAuthor() != $content->getAuthor()) {
$notify_users[] = $reply->getAuthor();
}
}
}
foreach($notify_users as $notify_user) {
//forum_email
$pooled = $emailHelper->sendEmail($notify_user->getEmail(), "New Reply to one of your Forum Topics", [
["p" => "Hello {$notify_user},"],
["p" => "{$content->getAuthor()} has replied to the forum topic <a href=\"{$topic->getFullURL()}\">\"{$topic->getTitle()}\"</a> with the following reply:"],
["p" => "{$content->getContentFull()}"],
//["a" => ["href" => "staging.rooferscoffeeshop.com/forum/topic/{$topic->getSlug()}/unsubscribe/{$notify_user->getId()}", "text" => "Click Here to stop receiving these notifications"]],
["a" => ["href" => "rooferscoffeeshop.com/forum/topic/{$topic->getSlug()}/unsubscribe/{$notify_user->getId()}", "text" => "Click Here to stop receiving these notifications"]],
], [], "", "lauren@rooferscoffeeshop.com");
}
$session = $request->getSession();
$route = $session->get("this_route");
// return $this->redirectToRoute('task_success');
return $this->redirect($route["path"]);
}
else {
//failed the recaptcha check
$session = $request->getSession();
$route = $session->get("this_route");
return $this->redirect($route["path"]);
}
}
}
$count = $helper->countActiveChildren($topic);
return $this->contentMembersOnlyCheck($forum) ??
$this->defaultRender("content/content.html.twig", [
"meta" => [
"title" => $topic->getTitle(),
"breadcrumbs" => [
[
"title" => "Our Forums",
"href" => "/forum",
],
[
"title" => $forum->getTitle(),
"href" => "/forum/{$forum->getSlug()}",
],
[
"title" => $topic->getTitle(),
"href" => "/forum/topic/{$topic->getSlug()}",
],
],
],
"content" => $topic,
"replies" => $helper->getPaginatedChildren($topic, $limit, $page, false),
"limit" => $limit,
"pagenum" => $page,
"totalcount" => $count,
"totalpages" => ceil($count / $limit),
"baseurl" => $this->generateUrl('forum_topic', ['slug' => $slug]),
//"form" => $form->createView(),
//"unrestricted" => isset($unrestricted) ? $unrestricted : "",
//let everyone be unrestricted (Vickie wants everyone to be able to post images for now)
"unrestricted" => true,
]);
}
/**
* @Route("/forum/reply/{id}/{action}", name="forum_reply")
*/
public function forumReply(
Request $request,
ContentHelper $helper,
$id = "",
$action = ""
) {
$reply = $helper->getContentById($id);
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$user = $this->getUser();
if($user) {
if($reply->getAuthor() == $user || $user->isAdmin()) {
//access granted
//$unrestricted = $user->getUserMetaValueByKey("rich_editing");
if($action == "edit") {
if ($request->request->has("reply-content")) {
$content_full = $request->request->get("reply-content");
if(!$this->user->isAdmin()) {
$content_full = preg_replace('/<a[^>]+>([^<]+)<\/a>/i','\1',$content_full);
}
$reply->setContentFull($content_full);
$em = $this->getDoctrine()->getManager();
$em->persist($reply);
$em->flush();
$this->addFlash("success", "Reply has been updated.");
return $this->redirectToRoute("forum_topic", ["slug" => $reply->getPrnt()->getSlug(), "page" => "1"]);
}
return $this->defaultRender("content/tmpl/forum-reply-edit.html.twig", [
"content" => $reply,
//"unrestricted" => isset($unrestricted) ? $unrestricted : "",
"unrestricted" => true,
]);
}
elseif ($action == "delete"){
$reply->setStatus(Content::STATUS_INACTIVE);
$em = $this->getDoctrine()->getManager();
$em->persist($reply);
$em->flush();
$this->addFlash("success", "Reply has been deleted.");
return $this->redirectToRoute("forum_topic", ["slug" => $reply->getPrnt()->getSlug(), "page" => "1"]);
}
elseif ($action == "spam"){
$user = $reply->getAuthor();
if($user) {
$user->markAsSpam();
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$this->addFlash("success", "User has been marked as spam.");
}
else {
$this->addFlash("warning", "There was a problem marking this user as spam.");
}
return $this->redirectToRoute("forum_topic", ["slug" => $reply->getPrnt()->getSlug(), "page" => "1"]);
}
}
}
}
// no action was taken, return to the single reply view
return $this->defaultRender("content/tmpl/forum-reply-single.html.twig", [ // or content/content
"content" => $reply,
]);
}
/**
* @Route(
* "/forum/search/{search}/{page}",
* defaults={"search"="", "page"=1},
* name="forum_search",
* methods={"GET"}
* )
*/
public function forumSearch(
Request $request,
ContentHelper $helper,
$search = "",
$page = 1
) {
$limit = ContentHelper::FORUM_LIMIT;
$count = $helper->countForumSearchResults($search);
return $this->defaultRender("content/forum-search.html.twig", [
"meta" => [
"title" => "Forum Search Results",
],
"results" => $helper->getForumSearchResults($search, $limit, $page),
"search" => $search,
"limit" => $limit,
"pagenum" => $page,
"totalcount" => $count,
"totalpages" => ceil($count / $limit),
"baseurl" => $this->generateUrl('forum_search', ['search' => $search]),
]);
}
/**
* @Route("/forum/{slug}/{page}", name="forum")
*/
public function forum(
Request $request,
ContentHelper $helper,
UserHelper $userhelper,
EmailHelper $emailHelper,
$slug = "",
$page = 1
) {
$forum = $helper->getForumBySlug($slug);
$limit = ContentHelper::FORUM_LIMIT;
//if ($form->isSubmitted() && $form->isValid()) {
if ($request->request->has("content") && $request->request->has("title")) {
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$content = new Content();
$entityManager = $this->getDoctrine()->getManager();
$site = $entityManager
->getRepository(Site::class)
->findOneBy([
"id" => $this->site_code
]);
$content->addSite($site);
$content->setType(Content::FORUM_TOPIC);
$content->setPrnt($forum);
$content->setPermission(1);
$user = $this->getUser();
if($user) {
$content->setAuthor($user);
//$unrestricted = $user->getUserMetaValueByKey("rich_editing");
}
if($emailHelper->checkInvisibleCaptcha($request->get("g-recaptcha-response"))) {
$notify = new ContentMeta();
$notify->setMetakey("_notify_of_replies");
$request->request->has("notify") ? $notify->setMetavalue(1) : $notify->setMetavalue(0);
$content->addContentmetum($notify);
$content->setTitle($request->request->get("title"));
$content->setContentFull($request->request->get("content"));
$content->setSlug($helper->getUniqueSlug($content->getTitle(), "", Content::SITE_RCS));
if($helper->isSpam($request->request->get("title")) || $helper->isSpam($request->request->get("content"))) {
//Just preventing posting entirely for now instead of marking as in review since there is so much Korean spam.
//$content->setStatus(Content::STATUS_IN_REVIEW);
//$this->addFlash("warning", "Your new topic has triggered our automatic spam filter. If you believe this is an error, please contact a site administrator.");
$session = $request->getSession();
$route = $session->get("this_route");
return $this->redirect($route["path"]);
}
else {
//Not spam
$content->setStatus(Content::STATUS_ACTIVE);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($content);
$entityManager->flush();
$this->addFlash("success", "Your new topic \"{$content->getTitle()}\" has been added.");
$emailSent = false;
//If it's a members only topic, notify members who are set to receive notifications
if($forum->getMembersOnly()) {
$notify_users = $userhelper->getMembersToNotify("member_notification_forum");
if($notify_users) {
foreach($notify_users as $notify_user) {
//forum_email
$pooled = $emailHelper->sendEmail($notify_user->getEmail(), "New Members Only Forum Topic", [
["p" => "Hello {$notify_user},"],
["p" => "{$content->getAuthor()} has posted a new topic to the R-Club forum: \"<a href='{$content->getFullURL()}'>{$content->getTitle()}</a>\"."],
["p" => "{$content->getContentFull()}"],
["a" => ["href" => "rooferscoffeeshop.com/account", "text" => "Update your membership notification setting here to stop receiving these notifications"]],
], [], "", "lauren@rooferscoffeeshop.com");
$emailSent = true;
}
}
}
if(!$emailSent) {
//forum_email
$pooled = $emailHelper->sendEmail(SiteConfig::CONFIGS[$this->site_code]["email_group"], "New Forum Topic", [
//["p" => "Hello {$notify_user},"],
["p" => "{$content->getAuthor()} has posted a new topic to the forum: \"<a href='{$content->getFullURL($this->site_code)}'>{$content->getTitle()}</a>\"."],
["p" => "{$content->getContentFull()}"],
]);
}
}
}
else {
//failed the recaptcha check
$session = $request->getSession();
$route = $session->get("this_route");
return $this->redirect($route["path"]);
}
}
}
$count = $helper->countActiveChildren($forum);
return $this->contentMembersOnlyCheck($forum) ??
$this->defaultRender("content/content.html.twig", [
"meta" => [
"title" => $forum->getTitle(),
"breadcrumbs" => [
[
"title" => "Our Forums",
"href" => "/forum",
],
[
"title" => $forum->getTitle(),
"href" => "/forum/{$forum->getSlug()}",
],
],
],
"content" => $forum,
//"topics" => $helper->getPaginatedChildren($forum, $limit, $page),
"topics" => $helper->getTopicsByForum($forum, $limit, $page),
"limit" => $limit,
"pagenum" => $page,
"totalcount" => $count,
"totalpages" => ceil($count / $limit),
"baseurl" => $this->generateUrl('forum', ['slug' => $slug]),
//"form" => $form->createView(),
//"unrestricted" => isset($unrestricted) ? $unrestricted : "", //if the user can post unrestricted HTML content
"unrestricted" => true,
]);
}
//TODO: Keep here, or move to directory specific controller?
/**
* @Route("/be-part-of-the-directory/{part}/{purchaseItem}",
* name="directory-join-post",
* defaults={"part": 1, "purchaseItem": ""},
* methods={"POST"}
* )
*/
public function directoryJoinPost (
Request $request,
CategoryHelper $categoryHelper,
ContentHelper $contentHelper,
StorageInterface $storeInterface,
UserHelper $userHelper,
EmailHelper $emailHelper,
$part = 1,
$purchaseItem = ""
) {
$manager = $this->getDoctrine()->getManager();
$session = $request->getSession();
$user = $this->user;
// try to retrieve the current purchase item or create it
$purchase = null;
if ($user) {
$purchase = $this->user->getActivePurchase();
}
if (!$purchase) {
$purchase = $session->get("purchase_id");
if ($purchase) {
$purchase = $manager->getRepository(Purchase::class)
->findOneBy([
"id" => $purchase,
]);
if ($purchase) {
// make sure purchase is valid ...
if ($purchase->getStatus() != Purchase::STATUS_ACTIVE) {
$session->remove("purchase_id");
$purchase = null;
}
}
}
}
// if still no purchase ... we need to make one
if (!$purchase) {
$purchase = new Purchase();
}
$action = $request->get("action");
if ($action) {
if ($action == "edit_listing") {
return $this->redirectToRoute("directory-join", [
"part" => 2,
"purchaseItem" => $purchaseItem,
]);
}
else if ($action == "discard") {
$step = 1;
// should only remove if actively attached to the user object ... aka - in cart
$purchase = $user->getActivePurchase();
if ($purchase) {
$item = $purchase->getCurrentItem();
$purchase->removeItem($item);
$manager->persist($purchase);
$manager->flush();
$this->addFlash("success", "The item has successfully been removed from your <a href='/cart'>cart</a>.");
$session->remove("directory_type");
$session->remove("directory_product");
}
/*
$purchase = $user->getActivePurchase();
if ($purchase) {
$item = $purchase->getCurrentItem();
$purchase->removeItem($item);
$manager->persist($purchase);
$manager->flush();
$this->addFlash("success", "The item has successfully been removed from your <a href='/cart'>cart</a>.");
}
*/
return $this->redirectToRoute("directory-join", [
"part" => 1
]);
}
else if ($action == "add_to_cart") {
if ($user) {
$purchase = $user->getActivePurchase();
// purchase should be available here...
if ($purchase) {
$item = $purchase->getCurrentItem();
if ($item) {
$item->setStatus(PurchaseItem::STATUS_ACTIVE); //< not to be confused with STATUS_CURRENT
$manager->persist($purchase);
$manager->flush();
$session->remove("directory_product");
$session->remove("directory_type");
$session->remove("purchase_id");
$this->addFlash("success", "The item has successfully been added to your <a href='/cart'>cart</a>.");
}
}
return $this->redirectToRoute("cart", [
]);
} else {
$this->addFlash("warning", "Please sign-in.");
return $this->redirectToRoute("directory-join", [
"part" => "1",
]);
}
}
}
else if ($part == 1) {
// grab the type and subscription and store in session
$directory_type = $request->get("directory_type");
$directory_product = $request->get("directory_product");
$session->set("directory_type", $directory_type);
$session->set("directory_product", $directory_product);
$part = 2;
$product = $manager->getRepository(Product::class)
->findOneBy([
"id" => $directory_product,
]);
if ($purchaseItem) {
$item = $manager->getRepository(PurchaseItem::class)
->findOneBy([
"id" => $purchaseItem
]);
// make sure the current user can update the record
if ($item) {
$tempPurchase = $item->getPurchase();
if ($this->user &&
$product && (
$tempPurchase->getUser()->getId() == $this->user->getId()
)) {
$item->setProduct($product);
$manager->persist($tempPurchase);
$manager->flush();
// update the directory type too...
$content = $item->getContent();
$types = $content->getSecondaryCategoriesByTaxonomy("directory-type");
for ($i = 0; $i < count($types); $i++) {
$content->removeSecondaryCategory($types[$i]);
}
// now set the correct types
if ($content) {
for ($i = 0; $i < count($directory_type); $i++) {
//$cat = $categoryHelper->getCategoryById($directory_type[$i]);
//$content->addSecondaryCategory($cat);
}
}
$manager->persist($content);
$manager->flush();
}
}
}
else if ($purchase) {
$item = $purchase->getCurrentItem();
if ($item && $product) {
if ($item->getType() != PurchaseItem::TYPE_DIRECTORY) {
// if it's not a classified purchase ... create a new one...
// replace the current item
$item->setStatus(PurchaseItem::STATUS_ACTIVE);
$item = new PurchaseItem();
$item->setType(PurchaseItem::TYPE_DIRECTORY);
$purchase->setCurrentItem($item);
}
$item->setProduct($product);
$manager->persist($purchase);
$manager->flush();
// update the directory type too...
$content = $item->getContent();
if ($content) {
$types = $content->getSecondaryCategoriesByTaxonomy("directory-type");
for ($i = 0; $i < count($types); $i++) {
$content->removeSecondaryCategory($types[$i]);
}
// now set the correct types
if ($content) {
for ($i = 0; $i < count($directory_type); $i++) {
//$cat = $categoryHelper->getCategoryById($directory_type[$i]);
//$content->addSecondaryCategory($cat);
}
}
$manager->persist($content);
$manager->flush();
}
}
}
}
else if ($part == 2) {
// check that we have a user
if (!$user) {
$rUser = $request->get("account");
if ($rUser) {
// see about creating user
$resp = $userHelper->signUp(
$rUser["firstname"],
$rUser["lastname"],
$rUser["username"],
$rUser["email"],
$rUser["password1"],
$rUser["password2"]
);
// add the message
$this->addFlash($resp["message"]["type"], $resp["message"]["text"]);
// was there an error creating the user?
if (!$resp["status"]) {
$session->getFlashBag()->add("directory", $request->get("directory"));
return $this->redirectToRoute("directory-join", [
"part" => 2,
]);
}
// set user to the newly created user
$user = $resp["user"];
}
else {
// error - we need a user object
$session->getFlashBag()->add("directory", $request->get("directory"));
$this->addFlash("warning", "You must either sign into the system or provide details to create an account.");
return $this->redirectToRoute("directory-join", [
"part" => 2,
]);
}
return $this->redirectToRoute("directory-join", [
"part" => 2,
]);
}
// build out the directory object now
$rDirectory = $request->get("directory");
$item = null;
if ($purchaseItem) {
$item = $manager->getRepository(PurchaseItem::class)
->findOneBy([
"id" => $purchaseItem
]);
// does the item belong to the current user?
if (!$item || $item->getPurchase()->getUser()->getId() == $user->getId()) {
if ($item) {
// set purchase to the correct object
$purchase = $item->getPurchase();
}
} else {
$item = null;
$purchaseItem = null;
}
}
$purchase->setUser($user);
if (!$item) {
$item = $purchase->getCurrentItem();
// if no purchase item exists - create it
if (!$item) {
$item = new PurchaseItem();
$item->setStatus(PurchaseItem::STATUS_CURRENT);
$item->setType(PurchaseItem::TYPE_DIRECTORY);
}
}
$product_id = $session->get("directory_product");
$product = $item->getProduct();
if (!$product || ($product->getId() != $product_id && !$purchaseItem)) {
$product = $manager->getRepository(Product::class)
->findOneBy([
"status" => 1,
"id" => $product_id
]);
}
if (!$product) {
$this->addFlash("warning", "Please select a product.");
return $this->redirectToRoute("directory-join", [
"part" => 1
]);
}
$item->setProduct($product);
// set as current if not editing another record
if (!$purchaseItem) {
$purchase->setCurrentItem($item);
}
$content = $item->getContent();
if (!$content) {
$content = new Content();
$entityManager = $this->getDoctrine()->getManager();
$site = $entityManager
->getRepository(Site::class)
->findOneBy([
"id" => $this->site_code
]);
$content->addSite($site);
$content->setStatus(Content::STATUS_INACTIVE);
$customer = new Customer();
//$customer->setStatus(0);
$customer->setStatus(1);
$customer->setDirectoryContent($content);
}
else {
$customer = $content->getDirectory();
}
// build the directory per the provided data
$content->setAuthor($user);
$content->setType(Content::DIRECTORY);
$content->setTitle($rDirectory["title"]);
$customer->setTitle($rDirectory["title"]);
if (!$content->getSlug()) {
$content->setSlug($contentHelper->getUniqueSlug($rDirectory["title"], "", Content::SITE_RCS));
}
$content->setContentFull($rDirectory["description"]);
$content->setFeatured(0);
// location
/*
$meta = $content->getContentMetaByKey("_job_location");
if (!$meta) {
$meta = new ContentMeta();
$meta->setMetaKey("_job_location");
$meta->setMetaValue($rDirectory["location"]);
$content->addContentMetum($meta);
} else {
$meta->setMetaValue($rDirectory["location"]);
}
*/
// country
$meta = $content->getContentMetaByKey("_job_country");
if (!$meta) {
$meta = new ContentMeta();
$meta->setMetaKey("_job_country");
$meta->setMetaValue($rDirectory["country"]);
$content->addContentMetum($meta);
} else {
$meta->setMetaValue($rDirectory["country"]);
}
$content->resetSecondaryCategories();
// directory type(s)
//print_r($rDirectory["type"]);
$customer->setCustomerTypeArray($rDirectory["type"]);
//for ($i = 0; $i < count($rDirectory["type"]); $i++) {
//$category = $categoryHelper->getCategoryById($rDirectory["type"][$i]);
//$content->addSecondaryCategory($category);
//}
// directory category(ies)
for ($i = 0; $i < count($rDirectory["category"]); $i++) {
$category = $categoryHelper->getCategoryById($rDirectory["category"][$i]);
$content->addSecondaryCategory($category);
$customer->addCategory($category);
}
// company e-mail
$customer->setEmail($rDirectory["contact_email"]);
$meta = $content->getContentMetaByKey("_company_email");
if (!$meta) {
$meta = new ContentMeta();
$meta->setMetaKey("_company_email");
$meta->setMetaValue($rDirectory["contact_email"]);
$content->addContentMetum($meta);
} else {
$meta->setMetaValue($rDirectory["contact_email"]);
}
// directory keywords
$customer->setKeywords($rDirectory["keywords"]);
$meta = $content->getContentMetaByKey("_directory_keywords");
if (!$meta) {
$meta = new ContentMeta();
$meta->setMetaKey("_directory_keywords");
$meta->setMetaValue($rDirectory["keywords"]);
$content->addContentMetum($meta);
} else {
$meta->setMetaValue($rDirectory["keywords"]);
}
// distribution states / provinces (only for distributors / manufacturer reps)
if(is_array($rDirectory["type"]) && (in_array("Distributors", $rDirectory["type"]) || in_array("Manufacturers Reps", $rDirectory["type"]) )) {
if(isset($rDirectory["dstates"])) {
$customer->setState($rDirectory["dstates"]);
}
}
// phone
$customer->resetPhones();
if($rDirectory["phone"]) {
$phone = new CustomerPhone();
$phone->setTitle("Main Phone");
$phone->setNumber($rDirectory["phone"]);
$customer->addPhone($phone);
}
// address
$customer->resetAddresses();
if($rDirectory["address1"]) {
$address = new CustomerAddress();
$address->setTitle("Main Address");
$address->setAddressLine1($rDirectory["address1"] ? $rDirectory["address1"] : "");
$address->setAddressLine2($rDirectory["address2"] ? $rDirectory["address2"] : "");
$address->setCity($rDirectory["city"] ? $rDirectory["city"] : "");
$address->setStateProvince($rDirectory["state"] ? $rDirectory["state"] : "");
$address->setPostalCode($rDirectory["zip"] ? $rDirectory["zip"] : "");
$address->setCountry($rDirectory["country"] ? $rDirectory["country"] : "");
$customer->addAddress($address);
}
$meta = $content->getContentMetaByKey("_company_phone");
if (!$meta) {
$meta = new ContentMeta();
$meta->setMetaKey("_company_phone");
$meta->setMetaValue($rDirectory["phone"]);
$content->addContentMetum($meta);
} else {
$meta->setMetaValue($rDirectory["phone"]);
}
// company contact
$meta = $content->getContentMetaByKey("_company_contact");
if (!$meta) {
$meta = new ContentMeta();
$meta->setMetaKey("_company_contact");
$meta->setMetaValue($rDirectory["contact"]);
$content->addContentMetum($meta);
} else {
$meta->setMetaValue($rDirectory["contact"]);
}
// website
$customer->setWebsite($rDirectory["website"]);
$meta = $content->getContentMetaByKey("_company_website");
if (!$meta) {
$meta = new ContentMeta();
$meta->setMetaKey("_company_website");
$meta->setMetaValue($rDirectory["website"]);
$content->addContentMetum($meta);
} else {
$meta->setMetaValue($rDirectory["website"]);
}
// twitter
$customer->setTwitter($rDirectory["twitter"]);
$meta = $content->getContentMetaByKey("_company_twitter");
if (!$meta) {
$meta = new ContentMeta();
$meta->setMetaKey("_company_twitter");
$meta->setMetaValue($rDirectory["twitter"]);
$content->addContentMetum($meta);
} else {
$meta->setMetaValue($rDirectory["twitter"]);
}
// linkedin
$customer->setLinkedin($rDirectory["linkedin"]);
$meta = $content->getContentMetaByKey("_company_linkedin");
if (!$meta) {
$meta = new ContentMeta();
$meta->setMetaKey("_company_linkedin");
$meta->setMetaValue($rDirectory["linkedin"]);
$content->addContentMetum($meta);
} else {
$meta->setMetaValue($rDirectory["linkedin"]);
}
// facebook
$customer->setFacebook($rDirectory["facebook"]);
$meta = $content->getContentMetaByKey("_company_facebook");
if (!$meta) {
$meta = new ContentMeta();
$meta->setMetaKey("_company_facebook");
$meta->setMetaValue($rDirectory["facebook"]);
$content->addContentMetum($meta);
} else {
$meta->setMetaValue($rDirectory["facebook"]);
}
// instagram
$customer->setInstagram($rDirectory["instagram"]);
$meta = $content->getContentMetaByKey("_company_instagram");
if (!$meta) {
$meta = new ContentMeta();
$meta->setMetaKey("_company_instagram");
$meta->setMetaValue($rDirectory["instagram"]);
$content->addContentMetum($meta);
} else {
$meta->setMetaValue($rDirectory["instagram"]);
}
// youtube
$customer->setYoutube($rDirectory["youtube"]);
$meta = $content->getContentMetaByKey("_company_youtube");
if (!$meta) {
$meta = new ContentMeta();
$meta->setMetaKey("_company_youtube");
$meta->setMetaValue($rDirectory["youtube"]);
$content->addContentMetum($meta);
} else {
$meta->setMetaValue($rDirectory["youtube"]);
}
// check if uploaded a logo
$file = $request->files->get("directory");
$file = $file["logo"];
if ($file) {
// store the logo in the content object
//$content->setFeaturedImageData($file);
$mime = $file->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'));
}
$media = new Media();
$media->setTitle($rDirectory["title"]. " Directory Logo");
$media->setData($file);
$media->setDescription("Directory Logo");
$media->setName($file->getClientOriginalName());
$content->setMedia($media);
$customer->setMedia($media);
}
else if (!empty($rDirectory["remove_logo"])) {
// remove the image data
// $storeInterface->remove($content, new PropertyMapping("featured_image_data", "featured_image"));
//$content->removeFeaturedImage();
$content->setMedia(null);
$customer->setMedia(null);
}
// only set to in review when not already purchased ...
if (!$content->getStatus()) {
$content->setStatus(Content::STATUS_IN_REVIEW);
}
if (!$purchaseItem) {
$item = $purchase->getCurrentItem();
$item->setContent($content);
$purchase->setCurrentItem($item);
}
else {
$this->addFlash("success", "Listing Successfully Updated.");
//If someone edits an active listing, notify Vickie
if ($content->getStatus() == Content::STATUS_ACTIVE) {
$userText = "";
if ($user) {
$username = $user->getUsername();
$userText = "by ".$username;
}
$emailHelper->sendEmail(
["rcs@rooferscoffeeshop.com"],
"Directory Listing Updated - {$content->getTitle()}",
[
["p" => "The directory listing '{$content->getTitle()}' has been updated {$userText}."],
]
);
}
}
if ($purchase->getStatus() != Purchase::STATUS_PROCESSED) {
if (count($purchase->getCoupons())) {
//Removing these on 1-13-21 for update that allows applying coupons through a link.
//$purchase->removeCoupons();
//$this->addFlash("warning", "The coupons that were assigned to this order have been reset since the order was adjusted. You may add them back to the order from the checkout screen.");
}
// update all totals
// $purchase->setTotal($purchase->getTotal());
$purchase->setTotal($purchase->calculateTotal());
}
$manager->persist($purchase);
$manager->persist($content);
$manager->persist($customer);
$manager->flush();
$purchase_id = $purchase->getId();
$session->set("purchase_id", $purchase_id);
$part = 3;
}
return $this->redirectToRoute("directory-join", [
"part" => $part,
"purchaseItem" => $purchaseItem,
]);
}
/**
* @Route("/be-part-of-the-directory/{part}/{purchaseItem}",
* name="directory-join",
* defaults={"part": 1, "purchaseItem": ""}
* )
*/
public function directoryJoin (
Request $request,
CategoryHelper $categoryHelper,
$part = 1,
$purchaseItem = ""
) {
$user = $this->user;
$manager = $this->getDoctrine()->getManager();
$products = null;
$purchase = null;
$session = $request->getSession();
$directoryTypes = $categoryHelper->getCategoriesByTaxonomy("directory-type");
$chosenDirectoryTypes = $session->get("directory_type");
$chosenDirectoryProduct = $session->get("directory_product");
$directoryCategories = null;
$chosenDirectoryCategories = null;
$directory = null;
$options = null;
// will contain the request data if submitted data has errors
$tempItem = null;
$item = null;
// product id is only being grabbed from the session -
// ======================= TRY TO GRAB THE PURCHASE OBJECT ===================== //
// first grab the purchase item if provided in route and match to current user...
if ($purchaseItem && $this->user) {
$purchaseItem = $manager->getRepository(PurchaseItem::class)
->findOneBy([
"id" => $purchaseItem
]);
if ($purchaseItem) {
$temp = $purchaseItem->getPurchase();
if ($temp->getUser()->getId() == $this->user->getId()) {
$purchase = $temp;
} else {
$purchaseItem = null;
}
}
}
else if ($purchaseItem && !$this->user) {
$this->addFlash("warning", "Please log-in before editing your listing");
return $this->redirectToRoute("directory-join", [
"part" => 1,
"purchaseItem" => "",
]);
}
else {
$purchaseItem = null;
}
// if purchase still doesn't exist - grab the purchase object if it exists
if (!$purchase && $this->user) {
$purchase = $this->user->getActivePurchase();
}
// finally if purchase still doesn't exist - try to pull from the current session
if (!$purchase) {
$purchase = $session->get("purchase_id");
if ($purchase) {
$purchase = $manager->getRepository(Purchase::class)
->findOneBy([
"id" => $purchase,
]);
}
}
// ================== END OF TRY TO GRAB THE PURCHASE OBJECT ===================== //
// if we have a purchaseItem at this point it is valid.
if ($purchaseItem) {
$item = $purchaseItem;
} else {
$item = $purchase && $purchase->getCurrentItem() ? $purchase->getCurrentItem() : null;
}
// make sure we're looking at a directory item
if ($item && $item->getType() != PurchaseItem::TYPE_DIRECTORY) {
if ($purchaseItem) {
// kick them over to the correct listing classified form
return $this->redirectToRoute("post-classified", [
"step" => 1,
"purchaseItem" => $purchaseItem,
]);
}
else {
// adjust the "current" classified listing to be active instead
$item->setStatus(PurchaseItem::STATUS_ACTIVE);
$manager->persist($item);
$manager->flush();
// redirect to the main directory page again
return $this->redirectToRoute("directory-join");
}
}
// try to find what product we are looking at
if ($item && $item->getProduct()) {
$chosenDirectoryProduct = $item->getProduct();
}
if ($item && $item->getContent() && $item->getContent()->getSecondaryCategoriesByTaxonomy('directory-type')) {
$cats = $item->getContent()->getSecondaryCategoriesByTaxonomy('directory-type');
$temp = [];
for ($i = 0; $i < count($cats); $i++) {
$temp[] = $cats[$i]->getId();
}
if (!empty($temp)) {
$chosenDirectoryTypes = $temp;
}
}
if (is_numeric($chosenDirectoryProduct)) {
$chosenDirectoryProduct = $manager->getRepository(Product::class)
->findOneBy([
"status" => 1,
"id" => $chosenDirectoryProduct,
]);
}
if ($part == 1) {
if ($purchaseItem) {
$purchase = $purchaseItem->getPurchase();
// don't allow changing product from completed purchases
if ($purchase->getStatus() != Purchase::STATUS_ACTIVE) {
return $this->redirectToRoute("directory-join", [
"part" => 1,
]);
}
}
//products to display
$options = [];
$options[] = ["product" => $manager->getRepository(Product::class)->findOneBy(["slug" => "standard-directory-month"])];
$options[] = ["product" => $manager->getRepository(Product::class)->findOneBy(["slug" => "standard-directory-year"])];
if($user && $user->getMember() == User::MEMBERSHIP_COMPANY) {
$free_product_in_use = false;
$product = $manager->getRepository(Product::class)->findOneBy(["slug" => "free-standard-directory"]);
foreach($user->getPurchases() as $purchase) {
if($purchase->getStatus() == Purchase::STATUS_PROCESSED) {
foreach($purchase->getItems() as $pitem) {
if($product == $pitem->getProduct() && $pitem->getContent()) {
if($pitem->getContent()->getStatus() != Content::STATUS_TRASH) {
$free_product_in_use = true;
}
}
}
}
}
if($free_product_in_use) {
$options[] = [
"product" => $product,
"disabled" => true,
"class" => "disabled",
"description" => "Your free directory listing has already been redeemed. Manage your listing from your account page <a href='/account/content/4'>here</a>.",
];
}
else {
$options[] = ["product" => $product, "class" => "featured"];
}
}
$options[] = ["product" => $manager->getRepository(Product::class)->findOneBy(["slug" => "interactive-directory-month"])];
if(!$user || $user->getMember() != User::MEMBERSHIP_PREMIUM) {
$options[] = [
"product" => $manager->getRepository(Product::class)->findOneBy(["slug" => "premium-directory-month"]),
"disabled" => true,
/*"link" => "rcs-club-sign-up",*/
"extra_info" => "Included in R-Club Membership. <a href='/rcs-club-sign-up'>Click here</a> to sign up.",
];
}
else {
$free_product_in_use = false;
$product = $manager->getRepository(Product::class)->findOneBy(["slug" => "free-premium-directory"]);
foreach($user->getPurchases() as $purchase) {
if($purchase->getStatus() == Purchase::STATUS_PROCESSED) {
foreach($purchase->getItems() as $pitem) {
if($product == $pitem->getProduct() && $pitem->getContent()) {
if($pitem->getContent()->getStatus() != Content::STATUS_TRASH) {
$free_product_in_use = true;
}
}
}
}
}
if($free_product_in_use) {
$options[] = [
"product" => $product,
"disabled" => true,
"class" => "disabled",
"extra_info" => "Your free directory listing has already been redeemed. Manage your listing from your account page <a href='/account/content/4'>here</a>.",
];
}
else {
$options[] = [
"product" => $product,
"class" => "featured",
"extra_info" => "Select this option to create your interactive directory listing, included with your premium R-Club membership!",
];
}
}
$options = array_filter($options);
/*
$products = $manager->getRepository(Product::class)
->findBy([
"status" => 1,
"type" => 1 //< grab directory products
]);
*/
}
else if ($part == 2) {
$directoryCategories = $categoryHelper->getCategoriesByTaxonomy("directory-category");
if (!$chosenDirectoryProduct) {
$this->addFlash("warning", "Please select a product.");
return $this->redirectToRoute("directory-join", [
"part" => 1,
]);
}
}
else if ($part == 3) {
if ($purchaseItem) {
$directory = $purchaseItem->getContent();
} else if ($purchase && $purchase->getCurrentItem()) {
$item = $purchase->getCurrentItem();
$directory = $item->getContent();
} else {
// redirect to step one
$this->addFlash("warning", "No directory data found. Please fill out the form to create a directory listing.");
return $this->redirectToRoute("directory-join", [
"part" => 1
]);
}
}
/*
$content = $item->getContent();
$categories = $content->getSecondaryCategories();
for ($i = 0; $i < count($categories); $i++) {
var_dump($categories[$i]->getTitle());
}
exit;
*/
if (!$item) {
// check for tempItem
$tempItem = $session->getFlashBag()->get("directory");
if ($tempItem) {
$tempItem = $tempItem[0];
}
}
$disableTypeSelect = false;
if($chosenDirectoryProduct && (strpos($chosenDirectoryProduct->getTitle(), 'Free') !== false)) {
$chosenDirectoryTypes = [$categoryHelper->getCategoryBySlug("contractors")];
$disableTypeSelect = true;
}
$statesProvinces = Customer::STATES_PROVINCES;
$disableStateSelect = true;
if(is_array($chosenDirectoryTypes) && (in_array("Distributors", $chosenDirectoryTypes) || in_array("Manufacturers Reps", $chosenDirectoryTypes) )) {
$disableStateSelect = false;
}
return $this->defaultRender("forms/directory-join.html.twig", [
"part" => $part,
"item" => $item,
"tempItem" => $tempItem,
"options" => $options,
"content" => $directory,
"directoryTypes" => $directoryTypes,
"statesProvinces" => $statesProvinces,
"chosenDirectoryTypes" => $chosenDirectoryTypes,
"chosenDirectoryProduct" => $chosenDirectoryProduct,
"directoryCategories" => $directoryCategories,
"disableTypeSelect" => $disableTypeSelect,
"disableStateSelect" => $disableStateSelect,
// "chosenDirectoryCategories" => $chosenDirectoryCategories,
"purchaseItem" => $purchaseItem,
]);
}
//--R-Club Start--
/**
* @Route("/rcs-club-sign-up",
* name="rcs-club-sign-up-post",
* methods={"POST"}
* )
*/
public function rcsClubSignUpPost (
Request $request,
ContentHelper $contentHelper,
UserHelper $userHelper,
EmailHelper $emailHelper,
LeadHelper $leadHelper
) {
$product_id = $request->get("club_product_id");
if(!$product_id) {
$product_id = 19; //The id of the individual monthly club membership product
}
$user = $this->user;
$manager = $this->getDoctrine()->getManager();
if (!$user) {
$signType = $request->get("signType");
if($signType == "signIn") {
//Essentially a copy of the AuthController's sign-in-post function
$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,
]);
*/
return $this->redirectToRoute("rcs-club-sign-up");
}
/*
$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) {
$user = $userHelper->getUserById($result["uid"]);
if($user->isMember()) {
$this->addFlash("success", "You have successfully logged in - and your account is already an R-Club member!");
return $this->redirectToRoute("rcs-club-sign-up");
}
else {
$this->addFlash("success", "You have successfully logged in.");
}
}
else {
//$this->addFlash("warning", "Invalid credentials provided.");
$message = array (
"type" => "warning",
"text" => "Invalid credentials provided.",
);
/*
return $this->defaultRender("forms/sign-in.html.twig", [
"message" => $message,
]);
*/
return $this->redirectToRoute("rcs-club-sign-up");
}
//return new RedirectResponse($path);
}
elseif($signType == "signUp") {
//Essentially a copy of the AuthController's new-sign-up function
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.");
$content = $contentHelper->getPageBySlug("rcs-club-sign-up");
$manager = $this->getDoctrine()->getManager();
$products = $manager->getRepository(Product::class)
->findBy([
"status" => 1,
"type" => Product::PRODUCT_TYPE_MEMBERSHIP //< grab r-club products
]);
return $this->defaultRender("forms/rcs-club-sign-up.html.twig", [
"content" => $content,
"products" => $products,
"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.",
]
]);
/*
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,
$product_id //redirect to r-club checkout after activatino
);
if ($rsp["status"]) { //success
$siteSignupSuccess = true;
//return new RedirectResponse('/welcome-activation');
}
else {
//$this->addFlash("warning", $rsp["message"]);
$content = $contentHelper->getPageBySlug("rcs-club-sign-up");
$manager = $this->getDoctrine()->getManager();
$products = $manager->getRepository(Product::class)
->findBy([
"status" => 1,
"type" => Product::PRODUCT_TYPE_MEMBERSHIP //< grab r-club products
]);
return $this->defaultRender("forms/rcs-club-sign-up.html.twig", [
"content" => $content,
"products" => $products,
"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")))) {
//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');
}
// 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,
]],
]
);
}
// 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();
/*
//TODO: fix / test mailchimp signup
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');
}
*/
}
/*
//create a user
$rUser = $request->get("account");
if ($rUser) {
// see about creating user
$resp = $userHelper->signUp(
"bypass",
"bypass",
$rUser["username"],
$rUser["email"],
$rUser["password1"],
$rUser["password2"]
);
// add the message
$this->addFlash($resp["message"]["type"], $resp["message"]["text"]);
// set user to the newly created user
if(array_key_exists("user", $resp)) {
$user = $resp["user"];
}
return $this->redirectToRoute("rcs-club-sign-up");
}
*/
}
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($product_id));
$newItem->setType(PurchaseItem::TYPE_MEMBERSHIP);
$newItem->setPurchase($purchase);
// add to the current Item
$purchase->setCurrentItem($newItem);
$purchase->setUser($user);
$purchase->setDiscount(0);
$manager->persist($purchase);
$manager->flush();
return $this->redirectToRoute("purchase", [
]);
}
}
/**
* @Route("/rcs-club-sign-up",
* name="rcs-club-sign-up"
* )
*/
public function rcsClubSignUp (
Request $request,
ContentHelper $helper
) {
$content = $helper->getPageBySlug("rcs-club-sign-up");
$manager = $this->getDoctrine()->getManager();
$products = $manager->getRepository(Product::class)
->findBy([
"status" => 1,
"type" => Product::PRODUCT_TYPE_MEMBERSHIP //< grab r-club products
]);
return $this->defaultRender("forms/rcs-club-sign-up.html.twig", [
"content" => $content,
"products" => $products,
]);
}
/**
* @Route("/rcs-club-quick-sign-up",
* name="rcs-club-quick-sign-up-post",
* methods={"POST"}
* )
*/
public function rcsClubQuickSignUpPost (
Request $request,
ContentHelper $contentHelper,
UserHelper $userHelper,
EmailHelper $emailHelper,
LeadHelper $leadHelper
) {
//$product_id = 22; //The id of the company monthly club membership product
$user = $this->getUser();
if (!$this->isGranted('IS_AUTHENTICATED_REMEMBERED') || !$user || !$user->isAdmin()) {
return false;
}
$access = true;
$message = null;
$success = true;
$lead = $request->get("l");
$email = $lead["email"];
$email = trim($email);
$firstname = $lead["firstname"];
$lastname = $lead["lastname"];
$company = $lead["company"];
$phone = $lead["phone"];
$notes = $lead["notes"];
$product_id = $lead["club_product_id"];
$tmp = $userHelper->checkEmailForRClubQuickSignUp($email);
if (!$tmp["status"]) {
$message = [
"type" => "warning",
"text" => $tmp["message"],
];
$success = false;
}
if(empty($firstname)){
$message = [
"type" => "warning",
"text" => "Please enter your first name.",
];
$success = false;
}
if(empty($lastname)){
$message = [
"type" => "warning",
"text" => "Please enter your last name.",
];
$success = false;
}
if($success) {
// 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($product_id));
$newItem->setType(PurchaseItem::TYPE_MEMBERSHIP);
$newItem->setPurchase($purchase);
if($notes) {
$purchaseNote = new PurchaseNote();
$purchaseNote->setAuthorName("RCS Payment Gateway");
$purchaseNote->setAuthorEmail("admin@rooferscoffeeshop.com");
$purchaseNote->setDescription($notes);
$purchase->addPurchaseNote($purchaseNote);
}
// add to the current Item
$purchase->setCurrentItem($newItem);
$purchase->setUser($user);
$purchase->setDiscount(0);
$purchase->setAdminQuickPurchase(true);
$purchase->setFirstName($firstname);
$purchase->setLastName($lastname);
$purchase->setEmail($email);
$purchase->setPhone($phone);
$purchase->setCompany($company);
$manager = $this->getDoctrine()->getManager();
$manager->persist($newItem);
$manager->persist($purchase);
$manager->flush();
return $this->redirectToRoute("purchase", [
]);
}
else {
return $this->defaultRender("forms/rcs-club-quick-sign-up.html.twig", [
"access" => $access,
"message" => $message,
"email" => $email,
"firstname" => $firstname,
"lastname" => $lastname,
"company" => $company,
"phone" => $phone,
"notes" => $notes,
]);
}
}
/**
* @Route("/rcs-club-quick-sign-up",
* name="rcs-club-quick-sign-up",
* methods={"GET"}
* )
*/
public function rcsClubQuickSignUp (
Request $request,
ContentHelper $helper
) {
$access = false;
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$user = $this->getUser();
if($user) {
if($user->isAdmin()) {
$access = true;
}
}
}
/*
$content = $helper->getPageBySlug("rcs-club-sign-up");
$manager = $this->getDoctrine()->getManager();
$products = $manager->getRepository(Product::class)
->findBy([
"status" => 1,
"type" => Product::PRODUCT_TYPE_MEMBERSHIP //< grab r-club products
]);
*/
return $this->defaultRender("forms/rcs-club-quick-sign-up.html.twig", [
"access" => $access,
//"content" => $content,
//"products" => $products,
]);
}
/**
* @Route("/rcs-cares-choice",
* name="rcs-cares-choice-post",
* methods={"POST"}
* )
*/
public function rcsCaresChoicePost (
Request $request,
ContentHelper $contentHelper,
UserHelper $userHelper,
EmailHelper $emailHelper
) {
$user = $this->user;
$charity = $request->get("rcs_cares_charity");
$user->setUsermetum("rcs_cares_charity", $charity);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash("success", "Thank you for choosing a charity to support!");
$emailHelper->sendEmail(
["rcs@rooferscoffeeshop.com"],
"RCS Cares Charity Selected by {$user->getDisplayname()}",
[
["p" => "{$user->getDisplayname()} has chosen to support the following charity: {$charity}."],
["a" => ["href" => "rooferscoffeeshop.com/rcs-cares-choice", "text" => "Click here to view all supported charities."]],
]
);
//return $this->redirectToRoute("new-club-member");
return $this->redirectToRoute("catchall", [
"slug" => "new-club-member",
]);
}
/**
* @Route("/rcs-cares-choice",
* name="rcs-cares-choice"
* )
*/
public function rcsCaresChoice (
Request $request,
ContentHelper $helper,
UserHelper $userhelper
) {
//Members only check
if((!$this->user || (!$this->user->isMember() && !$this->user->isAdmin()))) {
$this->addFlash("warning", "This page is only accessible to RCS Club members. Continue below to become a member and access this page.");
return $this->redirectToRoute("rcs-club-sign-up");
}
$selected = $this->user->getUserMetaValueByKey("rcs_cares_charity");
//Get number that have been selected
$charities = [];
$metas = $userhelper->getAllUserMetaByKey("rcs_cares_charity");
foreach($metas as $meta) {
$charity = $meta->getMetavalue();
if(array_key_exists($charity, $charities)) {
$charities[$charity]++;
}
else {
$charities[$charity] = 1;
}
}
$access = false;
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$user = $this->getUser();
if($user) {
if($user->isAdmin()) {
$access = true;
}
}
}
return $this->defaultRender("forms/rcs-cares-choice.html.twig", [
"selected" => $selected,
"all_selected" => $charities,
"show_selected" => $access,
"charities" => [
"RUTHERFORD HOUSING PARTNERSHIP aka Women Roofers",
"RONALD McDONALD HOUSE CHARITIES",
"ROOFING ALLIANCE",
"MIKE ROWE WORKS",
"HELMETS TO HARDHATS",
"HABITAT FOR HUMANITY",
"DAVIS MEMORIAL FOUNDATION"
],
]);
}
//--R-Club End--
//Stop here 2022-03-07
/**
* @Route("/edit-a-classified-ad/{purchase_item}", name="edit-classified")
*/
public function editClassifiedListing (
Request $request,
$purchase_item = ""
) {
$manager = $this->getDoctrine()->getManager();
$purchaseItem = $manager->getRepository(PurchaseItem::class)
->findOneBy([
"id" => $purchase_item,
]);
// ----
die ("start here");
}
/**
* @Route("/post-a-classified-ad/{step}/{purchaseItem}",
* name="post-classified-post",
* defaults={"step":"1", "purchaseItem": ""},
* methods={"POST"}
* )
*/
public function postClassifiedListingPost (
Request $request,
CategoryHelper $categoryHelper,
ContentHelper $contentHelper,
UserHelper $userHelper,
EmailHelper $emailHelper,
$step = 1,
$purchaseItem = ""
) {
// update to pull purchase from user id if available.
$user = null;
// check if logged in
if ($this->user) {
$user = $this->user;
}
// handle all steps here ...
$manager = $this->getDoctrine()->getManager();
$session = $request->getSession();
$purchase = null;
$error = [];
// Only store the ID in the session - use doctrine for all else...
// this way if the user logs out and logs back in they can still see
// the pending purchase
if ($user) {
$purchase = $this->user->getActivePurchase();
}
if (!$purchase) {
$purchase = $session->get("purchase_id");
if ($purchase) {
$purchase = $manager->getRepository(Purchase::class)
->findOneBy([
"id" => $purchase,
]);
if ($purchase) {
// make sure purchase is valid ...
if ($purchase->getStatus() != Purchase::STATUS_ACTIVE) {
$session->remove("purchase_id");
$purchase = null;
}
}
}
}
// if still no purchase ... we need to make one
if (!$purchase) {
$purchase = new Purchase();
}
$action = $request->get("action");
if ($action) {
if ($action == "edit_listing") {
$step = 2;
}
else if ($action == "edit_product") {
$step = 1;
}
else if ($action == "discard") {
$step = 1;
$purchase = $user->getActivePurchase();
if ($purchase) {
$item = $purchase->getCurrentItem();
$purchase->removeItem($item);
if (count($purchase->getCoupons())) {
//$purchase->removeCoupons();
//$this->addFlash("warning", "The coupons that were assigned to this order have been reset since the order was adjusted. You may add them back to the order from the checkout screen.");
}
$manager->persist($purchase);
$manager->flush();
$this->addFlash("success", "The item has successfully been removed from your <a href='/cart'>cart</a>.");
}
return $this->redirectToRoute("post-classified", [
"step" => 1
]);
}
else if ($action == "add_to_cart") {
$purchase = $user->getActivePurchase();
if ($purchase) {
$item = $purchase->getCurrentItem();
if ($item) {
// this one might not be needed
if (count($purchase->getCoupons())) {
//$purchase->removeCoupons();
//$this->addFlash("warning", "The coupons that were assigned to this order have been reset since the order was adjusted. You may add them back to the order from the checkout screen.");
}
$item->setStatus(PurchaseItem::STATUS_ACTIVE); //< not to be confused with STATUS_CURRENT
$manager->persist($purchase);
$manager->flush();
// $session->remove("purchase_id"); - the purchase id is the
$session->remove("classified_id");
}
}
// go to the shopping cart page
return $this->redirectToRoute("post-classified", [
"step" => "1",
]);
}
}
// pick the product
else if ($step == 1) {
// store the product id in the session
//$product_id = $request->get("product");
//$product_id = $product_id["product_id"];
//Switching to dynamic classified ads - not based on products
$product_id = 34;
// make sure the product exists
$product = $manager->getRepository(Product::class)
->findOneBy([
"status" => 1,
"id" => $product_id
]);
//Get other options
$duration = $request->get("duration");
$graphic = $request->get("graphic");
$regions = $request->get("regions");
$sites = $request->get("sites");
$totalPrice = $request->get("total-price-input");
if ($product) {
// if purchase exists - set product in purchase
if ($purchase) {
$item = $purchase->getCurrentItem();
if ($item) {
if (count($purchase->getCoupons())) {
//$purchase->removeCoupons();
//$this->addFlash("warning", "The coupons that were assigned to this order have been reset since the order was adjusted. You may add them back to the order from the checkout screen.");
}
$item->setProduct($product);
//$details = [];
//$item->setDetails();
$manager->persist($purchase);
$manager->flush();
}
}
/*
$productOptionValues = $regions;
if($duration){
$productOptionValues[] = $duration;
}
if($graphic){
$productOptionValues[] = $graphic;
}
foreach($productOptionValues as $productOptionValueId) {
$productOptionValue = $manager->getRepository(ProductOptionValue::class)
->findOneBy([
"id" => $productOptionValueId
]);
if($productOptionValue) {
$item->addProductOptionValue($productOptionValue);
}
}
*/
//TODO: move away from session vars?
// set in the session
$session->set("classified_id", $product_id);
// set some other stuff in the session for the next step
$session->set("duration", $duration);
$session->set("graphic", $graphic);
$session->set("regions", $regions);
$session->set("sites", $sites);
$session->set("totalPrice", $totalPrice);
// move on to step 2
$step = 2;
}
else {
$error = [
"message" => "Please select a valid product from the list provided."
];
}
}
// submit the details
else if ($step == 2) {
if (!$user) {
$rUser = $request->get("account");
if ($rUser) {
// see about creating user
$resp = $userHelper->signUp(
$rUser["firstname"],
$rUser["lastname"],
$rUser["username"],
$rUser["email"],
$rUser["password1"],
$rUser["password2"]
);
// add the message
$this->addFlash($resp["message"]["type"], $resp["message"]["text"]);
// was there an error creating the user?
if (!$resp["status"]) {
$session->getFlashBag()->add("listing", $request->get("listing"));
return $this->redirectToRoute("post-classified", [
"step" => 2,
]);
}
// set user to the newly created user
$user = $resp["user"];
}
else {
// error - we need a user object
$this->addFlash("warning", "You must either <a href='/sign-in'>sign</a> into the system or provide details to create an account.");
return $this->redirectToRoute("post-classified", [
"step" => 2,
]);
}
}
else {
$item = null;
if ($purchaseItem) {
$item = $manager->getRepository(PurchaseItem::class)
->findOneBy([
"id" => $purchaseItem
]);
// does the item belong to the current user?
if (!$item || $item->getPurchase()->getUser()->getId() == $user->getId()) {
if ($item) {
// set to the correct purchase object
$purchase = $item->getPurchase();
}
} else {
$item = null;
$purchaseItem = null;
}
}
// set the user into the purchase
$purchase->setUser($user);
// by this point we should have a user id that we can link the purchase into
// $purchaseItem = $purchase->getCurrentItem();
$durationId = $request->get("duration");
$graphicId = $request->get("graphic");
$regionIds = $request->get("regions");
$siteIds = $request->get("sites");
$totalPrice = $request->get("total-price-input");
$durationObject = $manager->getRepository(ProductOptionValue::class)
->findOneBy([
"id" => $durationId
]);
$graphicObject = $manager->getRepository(ProductOptionValue::class)
->findOneBy([
"id" => $graphicId
]);
$regionObjects = [];
foreach($regionIds as $regionId) {
$regionObject = $manager->getRepository(ProductOptionValue::class)
->findOneBy([
"id" => $regionId
]);
$regionObjects[] = $regionObject;
if($regionObject->getValue() == "All Regions") {
$allRegions = true;
}
}
$siteObjects = [];
foreach($siteIds as $siteId) {
$siteObject = $manager->getRepository(ProductOptionValue::class)
->findOneBy([
"id" => $siteId
]);
$siteObjects[] = $siteObject;
}
if (!$item) {
$item = $purchase->getCurrentItem();
if (!$item) {
$item = new PurchaseItem();
$item->setStatus(PurchaseItem::STATUS_CURRENT);
$item->setType(PurchaseItem::TYPE_CLASSIFIED);
if($durationObject) {
$item->addProductOptionValue($durationObject);
}
if($graphicObject) {
$item->addProductOptionValue($graphicObject);
}
foreach($regionObjects as $regionObject) {
$item->addProductOptionValue($regionObject);
}
foreach($siteObjects as $siteObject) {
$item->addProductOptionValue($siteObject);
}
}
}
/*
if(empty($item->getProductOptionValues())) {
if($durationObject) {
$item->addProductOptionValue($durationObject);
}
if($graphicObject) {
$item->addProductOptionValue($graphicObject);
}
foreach($regionObjects as $regionObject) {
$item->addProductOptionValue($regionObject);
}
foreach($siteObjects as $siteObject) {
$item->addProductOptionValue($siteObject);
}
}
*/
$product_id = $session->get("classified_id");
// set the product in the purchaseItem
$product = $item->getProduct();
if (!$product || ($product->getId() != $product_id && !$purchaseItem)) {
$product = $manager->getRepository(Product::class)
->findOneBy([
"status" => 1,
"id" => $product_id
]);
}
// update the product incase it changed
$item->setProduct($product);
if (!$purchaseItem) {
$purchase->setCurrentItem($item);
}
// create temporary listing
$listing = $request->get("listing");
$content = $item->getContent();
if (!$content) {
$content = new Content();
foreach($siteObjects as $siteObject) {
$site = $manager
->getRepository(Site::class)
->findOneBy([
"id" => Site::getSiteIdByCode($siteObject->getValue())
]);
if($site) {
$content->addSite($site);
}
}
if(empty($siteObjects)) {
$entityManager = $this->getDoctrine()->getManager();
$site = $entityManager
->getRepository(Site::class)
->findOneBy([
"id" => $this->site_code
]);
$content->addSite($site);
}
$content->setStatus(Content::STATUS_INACTIVE);
}
// build the classified listing per the selected product
$content->setAuthor($user);
$content->setType(Content::CLASSIFIED);
$content->setTitle($listing["title"]);
//Auto populate Customers field if an R-Club member
if($user->isMember()) {
$customers = $user->getCompanies();
if(!empty($customers)) {
foreach($customers as $customer) {
$content->addCustomer($customer);
}
}
}
if (!$content->getSlug()) {
$content->setSlug($contentHelper->getUniqueSlug($listing["title"], "", Content::SITE_RCS));
}
$content->setContentFull($listing["description"]);
$content->setFeatured(0);
$content->resetSecondaryCategories();
if (stripos($product->getTitle(), "featured") != false || ($graphicObject && $graphicObject->getValue() == "featured")) {
$content->setFeatured(1);
}
$meta = $content->getContentMetaByKey("_job_location");
if (!$meta) {
$meta = new ContentMeta();
$meta->setMetaKey("_job_location");
$meta->setMetaValue($listing["location"]);
$content->addContentMetum($meta);
} else {
$meta->setMetaValue($listing["location"]);
}
$regions = $listing["region"];
foreach ($regions as $region) {
$region = $categoryHelper->getCategoryById($region);
$content->addSecondaryCategory($region);
}
$meta = $content->getContentMetaByKey("_job_country");
if(array_key_exists("country", $listing)) {
if (!$meta) {
$meta = new ContentMeta();
$meta->setMetaKey("_job_country");
$meta->setMetaValue($listing["country"]);
$content->addContentMetum($meta);
} else {
$meta->setMetaValue($listing["country"]);
}
}
/* TODO - allow multiple categories? */
$category = $categoryHelper->getCategoryById($listing["category"]);
$content->addSecondaryCategory($category);
$content->setContentFull($listing["description"]);
$meta = $content->getContentMetaByKey("_company_email");
if (!$meta) {
$meta = new ContentMeta();
$meta->setMetaKey("_company_email"); //< double check meta key ... doesn't look to be being used
$meta->setMetaValue($listing["email"]);
$content->addContentMetum($meta);
} else {
$meta->setMetaValue($listing["email"]);
}
// _application - same as above but
$meta = $content->getContentMetaByKey("_application");
if (!$meta) {
$meta = new ContentMeta();
$meta->setMetaKey("_application");
$meta->setMetaValue($listing["email"]);
$content->addContentMetum($meta);
} else {
$meta->setMetaValue($listing["email"]);
}
// resume or file
$files = $request->files->get("listing");
// set image file if provided
if (isset($files["image"])) {
$image = $files["image"];
//$content->setFeaturedImageData($image);
$mime = $image->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'));
}
$media = new Media();
$media->setTitle($listing["file_title"]);
$media->setData($image);
$media->setDescription("Classified Listing File");
$media->setName($image->getClientOriginalName());
$content->setMedia($media);
}
else if (!empty($listing["remove_image"]) /* || stripos($product->getTitle(), 'includes image') === false*/ ) {
//$content->removeFeaturedImage();
$content->setMedia(null);
}
/*
else if (
(
!empty($listing["remove_image"]) ||
stripos($product->getTitle(), 'includes image') === false
) && $content->getFeaturedImageURL()
) {
$content->removeFeaturedImage();
}
*/
// set video file if provided
if (isset($files["video"])) {
$video = $files["video"];
$mime = $video->getMimeType();
if(!in_array($mime, ["video/mp4", "video/mp4"])) {
//$this->addFlash("danger", "This video file format is not allowed.");
//return new RedirectResponse($request->headers->get('referer'));
}
$videoMedia = new Media();
$videoMedia->setTitle($video->getClientOriginalName());
$videoMedia->setData($video);
$videoMedia->setDescription("Classified Listing Video File");
$videoMedia->setName($video->getClientOriginalName());
$content->setVideoMedia($videoMedia);
}
else if (!empty($listing["remove_video"]) /*|| stripos($product->getTitle(), 'video') === false */ ) {
$content->setVideoMedia(null);
}
if (!empty($listing["remove_file"])) {
$containers = $content->getMediaGroupContainers();
foreach($containers as $container) {
$group = $container->getMediaGroup();
if($group->getTitle() == "Classified Listing Files") {
$items = $group->getMediaGroupItems();
foreach($items as $item) {
$media = $item->getMedia();
$media->removeFile();
}
$em = $this->getDoctrine()->getManager();
$em->remove($container);
$em->flush();
}
}
/*
$group = $content->getMediaGroups();
for ($i = 0; $i < count($group); $i++) {
$items = $group[$i]->getMediaGroupItems();
for ($j = 0; $j < count($items); $j++) {
$media = $items[$j]->getMedia();
$media->removeFile();
}
$content->removeMediaGroup($group[$i]);
}
*/
}
$file = $files["file"];
if ($file) {
//copying this from above... to remove older file before adding new one
$containers = $content->getMediaGroupContainers();
foreach($containers as $container) {
$group = $container->getMediaGroup();
if($group->getTitle() == "Classified Listing Files") {
$items = $group->getMediaGroupItems();
foreach($items as $item) {
$media = $item->getMedia();
$media->removeFile();
}
$em = $this->getDoctrine()->getManager();
$em->remove($container);
$em->flush();
}
}
// upload the image
// - using a media group in case we need to store more files in the future.
$media = new Media();
$media->setTitle($listing["file_title"]);
$media->setData($file);
$media->setDescription("Classified Listing File");
$media->setName($file->getClientOriginalName());
$mediaGroupItem = new MediaGroupItem();
$mediaGroupItem->setTitle("Classified Listing File");
$mediaGroupItem->setDescription("Classified Listing File");
$mediaGroupItem->setMedia($media);
$mediaGroup = new MediaGroup();
$mediaGroup->setTitle("Classified Listing Files");
$mediaGroup->setDescription("Classified Listing Files");
$mediaGroup->addMediaGroupItem($mediaGroupItem);
$mediaGroupContainer = new MediaGroupContainer();
$mediaGroupContainer->setMediaGroup($mediaGroup);
$mediaGroupContainer->setContent($content);
$em = $this->getDoctrine()->getManager();
$em->persist($mediaGroupContainer);
$em->flush();
//$content->setMediaGroups(new ArrayCollection([$mediaGroup]));
//$content->addMediaGroup($mediaGroup);
$meta = $content->getContentMetaByKey("_file_title");
if (!$meta) {
$meta = new ContentMeta();
$meta->setMetaKey("_file_title");
$meta->setMetaValue($listing["file_title"]);
$content->addContentMetum($meta);
} else {
$meta->setMetaValue($listing["file_title"]);
}
}
$meta = $content->getContentMetaByKey("_company_contact");
if (!$meta) {
$meta = new ContentMeta();
$meta->setMetaKey("_company_contact");
$meta->setMetaValue($listing["contact"]);
$content->addContentMetum($meta);
} else {
$meta->setMetaValue($listing["contact"]);
}
$meta = $content->getContentMetaByKey("_company_phone");
if (!$meta) {
$meta = new ContentMeta();
$meta->setMetaKey("_company_phone");
$meta->setMetaValue($listing["phone"]);
$content->addContentMetum($meta);
} else {
$meta->setMetaValue($listing["phone"]);
}
$meta = $content->getContentMetaByKey("_company_name");
if (!$meta) {
$meta = new ContentMeta();
$meta->setMetaKey("_company_name");
$meta->setMetaValue($listing["company"]);
$content->addContentMetum($meta);
} else {
$meta->setMetaValue($listing["company"]);
}
$meta = $content->getContentMetaByKey("_company_website");
if (!$meta) {
$meta = new ContentMeta();
$meta->setMetaKey("_company_website");
$meta->setMetaValue($listing["website"]);
$content->addContentMetum($meta);
} else {
$meta->setMetaValue($listing["website"]);
}
if (!$content->getStatus()) {
$content->setStatus(Content::STATUS_IN_REVIEW);
}
// $content->setAuthor($user); //< this was already done above
// if errors - go back and show
// if no errors - move on
if (!$purchaseItem) {
$item = $purchase->getCurrentItem();
$item->setContent($content);
$purchase->setCurrentItem($item);
}
else {
$this->addFlash("success", "Listing Successfully Updated.");
//If someone edits an active listing, notify Vickie
if ($content->getStatus() == Content::STATUS_ACTIVE) {
$userText = "";
if ($user) {
$username = $user->getUsername();
$userText = "by ".$username;
}
$emailHelper->sendEmail(
["rcs@rooferscoffeeshop.com"],
"Classified Listing Updated - {$content->getTitle()}",
[
["p" => "The classified listing '{$content->getTitle()}' has been updated {$userText}."],
]
);
}
}
if ($purchase->getStatus() != Purchase::STATUS_PROCESSED) {
if (count($purchase->getCoupons())) {
//$purchase->removeCoupons();
//$this->addFlash("warning", "The coupons that were assigned to this order have been reset since the order was adjusted. You may add them back to the order from the checkout screen.");
}
// set the proper total
// $purchase->setTotal($purchase->getTotal());
$purchase->setTotal($purchase->calculateTotal());
}
// update the parent purchase item
$manager->persist($purchase);
$manager->flush();
$purchase_id = $purchase->getId();
$session->set("purchase_id", $purchase_id);
// sessions do not store relational data well - we are going to use the database and link it to the user
// $session->set($purchase);
$step = 3;
}
}
// add the listing to the cart
else if ($step == 3) {
// if updating another purchase item
if ($purchaseItem) {
}
// adding purchase item to cart
else {
if (count($purchase->getCoupons())) {
//$purchase->removeCoupons();
//$this->addFlash("warning", "The coupons that were assigned to this order have been reset since the order was adjusted. You may add them back to the order from the checkout screen.");
}
$item = $purchase->getCurrentItem();
$item->setStatus(PurchaseItem::STATUS_ACTIVE);
$manager->persist($purchase);
$manager->flush();
// $session->remove("purchase_id"); - the purchase id is the
$session->remove("classified_id");
}
// go to the shopping cart page
return $this->redirectToRoute("cart", [
"slug" => "list",
]);
}
return $this->redirectToRoute("post-classified", [
"step" => $step,
"purchaseItem" => $purchaseItem
]);
}
/**
* @Route("/post-a-classified-ad/{step}/{purchaseItem}",
* name="post-classified",
* defaults={"step": "1", "purchaseItem": ""}
* )
*
*/
public function postClassifiedListing (
Request $request,
CategoryHelper $categoryHelper,
$step = 1,
$purchaseItem = ""
) {
/* 2018.07.31 - forcing user account to access page
if (!$this->user) {
die("need to log in");
}
*/
$session = $request->getSession();
$manager = $this->getDoctrine()->getManager();
$purchase = null;
$tempListing = $session->getFlashBag()->get("listing");
if (!empty($tempListing)) {
$tempListing = $tempListing[0];
}
// ==== GRAB CURRENT PURCHASE OBJECT ========= //
// first grab the purchase item if provided in route and match to current user...
if ($purchaseItem && $this->user) {
$purchaseItem = $manager->getRepository(PurchaseItem::class)
->findOneBy([
"id" => $purchaseItem
]);
if ($purchaseItem) {
$temp = $purchaseItem->getPurchase();
if ($temp->getUser()->getId() == $this->user->getId()) {
$purchase = $temp;
} else {
$purchaseItem = null;
}
}
}
else if ($purchaseItem && !$this->user) {
$this->addFlash("warning", "Please log-in before editing your listing");
return $this->redirectToRoute("post-classified", [
"step" => 1,
"purchaseItem" => "",
]);
}
else {
$purchaseItem = null;
}
// if purchase still doesn't exist - grab the purchase object if it exists
if (!$purchase && $this->user) {
$purchase = $this->user->getActivePurchase();
}
// finally if purchase still doesn't exist - try to pull from the current session
if (!$purchase) {
$purchase = $session->get("purchase_id");
if ($purchase) {
$purchase = $manager->getRepository(Purchase::class)
->findOneBy([
"id" => $purchase,
]);
}
}
// ========= END OF GRAB PURCHASE ITEM ======== //
if ($purchaseItem && $purchaseItem->getType() != PurchaseItem::TYPE_CLASSIFIED) {
// redirect to the proper editing page
return $this->redirectToRoute("directory-join", [
"part" => 2,
"purchaseItem" => $purchaseItem->getId(),
]);
}
if ($purchase) {
// if we're looking at a current item make sure we're looking at a classified listing item
$item = $purchase->getCurrentItem();
if ($item && $item->getType() != PurchaseItem::TYPE_CLASSIFIED) {
$item->setStatus(PurchaseItem::STATUS_ACTIVE);
$manager->persist($item);
$manager->flush();
return $this->redirectToRoute("post-classified");
}
}
$listing = null;
$regions = null;
$categories = null;
$product = null;
$products = $manager->getRepository(Product::class)
->findBy([
"status" => 1,
"type" => 2
], [
"price" => "ASC"
]);
// update to grab values from session
if ($step == 1) {
if ($purchaseItem) {
if ($purchaseItem->getStatus() != PurchaseItem::STATUS_CURRENT) {
return $this->redirectToRoute("post-classified");
}
}
// check if we previously started a purchase...
if ($purchase) {
$temp = $purchase->getCurrentItem();
if ($temp) {
$purchaseItem = $temp;
$product = $purchaseItem->getProduct();
}
}
}
else if ($step == 2) {
$regions = $categoryHelper->getCategoriesByTaxonomy("job_listing_type");
$categories = $categoryHelper->getCategoriesByTaxonomy("job_listing_category");
$durationId = "";
$graphicId = "";
$regionIds = [];
$siteIds = [];
if ($purchaseItem) {
$listing = $purchaseItem->getContent();
$product = $purchaseItem->getProduct();
$productOptionValues = $purchaseItem->getProductOptionValues();
foreach($productOptionValues as $productOptionValue) {
if ($productOptionValue->getProductOption()->getId() == 1) { //duration
$durationId = $productOptionValue->getId();
}
if ($productOptionValue->getProductOption()->getId() == 2) { //graphic
$graphicId = $productOptionValue->getId();
}
if ($productOptionValue->getProductOption()->getId() == 3) { //regions
$regionIds[] = $productOptionValue->getId();
}
if ($productOptionValue->getProductOption()->getId() == 4) { //sites
$siteIds[] = $productOptionValue->getId();
}
}
}
else {
if ($purchase && $purchase->getCurrentItem()) {
$item = $purchase->getCurrentItem();
$listing = $item->getContent();
$product = $item->getProduct();
}
else {
$product_id = $session->get("classified_id");
if ($product_id) {
$product = $manager->getRepository(Product::class)
->findOneBy([
"id" => $product_id,
]);
}
}
}
//TODO: Why using session variables? Look into changing this.
if(!$durationId) {
$durationId = $session->get("duration");
}
if(!$graphicId) {
$graphicId = $session->get("graphic");
}
if(empty($regionIds)) {
$regionIds = $session->get("regions");
}
if(!$regionIds) {
$regionIds = [];
}
if(empty($siteIds)) {
$siteIds = $session->get("sites");
}
if(!$siteIds) {
$siteIds = [];
}
$totalPrice = $session->get("totalPrice");
//TODO: calculate total price when editing
$durationObject = $manager->getRepository(ProductOptionValue::class)
->findOneBy([
"id" => $durationId
]);
$graphicObject = $manager->getRepository(ProductOptionValue::class)
->findOneBy([
"id" => $graphicId
]);
$regionObjects = [];
foreach($regionIds as $regionId) {
$regionObject = $manager->getRepository(ProductOptionValue::class)
->findOneBy([
"id" => $regionId
]);
$regionObjects[] = $regionObject;
if($regionObject->getValue() == "All Regions") {
$allRegions = true;
}
}
$siteObjects = [];
foreach($siteIds as $siteId) {
$siteObject = $manager->getRepository(ProductOptionValue::class)
->findOneBy([
"id" => $siteId
]);
$siteObjects[] = $siteObject;
}
if (!$product) {
$this->addFlash("warning", "Please select a product.");
return $this->redirectToRoute("post-classified", [
"step" => 1
]);
}
}
else if ($step == 3) {
if ($purchaseItem) {
$listing = $purchaseItem->getContent();
$product = $purchaseItem->getProduct();
}
else {
/*
$items = $purchase->getItems();
foreach ($items as $item) {
var_dump($item->getStatusText());
}
*/
$item = $purchase->getCurrentItem();
if ($item) {
$listing = $item->getContent();
$product = $item->getProduct();
} else {
return $this->redirectToRoute("post-classified");
}
}
}
return $this->defaultRender("forms/classified-listing.html.twig", [
"products" => $products,
"product" => $product,
"durationId" => $durationId ?? "",
"graphicId" => $graphicId ?? "",
"regionIds" => $regionIds ?? "",
"siteIds" => $siteIds ?? "",
"durationObject" => $durationObject ?? "",
"graphicObject" => $graphicObject ?? "",
"regionObjects" => $regionObjects ?? "",
"siteObjects" => $siteObjects ?? "",
"allRegions" => $allRegions ?? false,
"totalPrice" => $totalPrice ?? "",
"regions" => $regions,
"categories" => $categories,
"listing" => $listing,
"tempListing" => $tempListing,
"purchaseItem" => $purchaseItem,
"user" => $this->user,
"step" => $step,
"meta" => [
"title" => "Post a Classified Ad",
"breadcrumbs" => [
[
"title" => "Post a Classified Ad",
"href" => "/post-a-classified-ad",
]
]
]
]);
}
}