src/Controller/Master/ContentController.php line 1174
<?php
namespace App\Controller\Master;
use App\Controller\Master\DefaultController as DefaultController;
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\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Form\Forms;
use Doctrine\Common\Collections\Criteria;
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\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 App\Utils\QuizHelper;
use App\Utils\MailChimpHelper;
use App\Utils\HootsuiteHelper;
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 Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient;
use Google\Analytics\Data\V1beta\DateRange;
use Google\Analytics\Data\V1beta\Dimension;
use Google\Analytics\Data\V1beta\Metric;
use Google\Analytics\Data\V1beta\RunReportRequest;
use Twig\Environment;
//TODO: Clean up uses in all controllers
class ContentController extends DefaultController
{
/**
* @Route("/uptime")
*/
public function uptime(
Request $request
) {
$stmt = $this->getDoctrine()->getManager()->getConnection()->query("SELECT 1 + 1 as res");
$res = $stmt->fetch();
return new JsonResponse($res["res"], 200, [], true);
}
/**
* @Route("/content-queue-test")
*/
public function contentQueueTest(
Request $request,
ContentHelper $contentHelper
) {
$session = $request->getSession();
$content_ids = $session->get("queued_content_ids", []);
return new JsonResponse(implode(", ", $content_ids), 200, [], true);
}
/**
* @Route("/content-queue-clear")
*/
public function contentQueueClear(
Request $request,
ContentHelper $contentHelper
) {
$session = $request->getSession();
$session->remove("queued_content_ids");
return new JsonResponse("OK", 200, [], true);
}
//TODO: RCS only?
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");
}
}
//TODO: Why are these needed for admin edit routes?
// & move this to a different controller
/**
* @Route("/ckeditor_upload", name="ckeditor_upload")
*/
public function ckeditor_upload (
Request $request
) {
}
/**
* @Route("/ckeditor_browse", name="ckeditor_browse")
*/
public function ckeditor_browse (
Request $request
) {
return $this->defaultRender("easy_admin/file-browse.html.twig", [
]);
}
// displays the meet the rcs influencers page
// requires a content object to be passed as $content
public function meetinfluencers(
Request $request,
ContentHelper $helper,
CustomerHelper $customerHelper,
$content = ""
) {
$cat_id = 479;
if($this->site_code == 3) {//SiteConfig::SITE_MCS
$cat_id = 1346;
}
if($this->site_code == 4) { //SiteConfig::SITE_CCS
$cat_id = 1445;
}
$customers = $customerHelper->getCustomersByCategory($cat_id, $this->site_code);
return $this->defaultRender("content/tmpl/meet-rcs-influencers.html.twig", [
"content" => $content,
"customers" => $customers,
]);
}
// displays the podcasts list page
public function podcasts(
Request $request,
ContentHelper $helper,
MediaHelper $mediaHelper,
$content = ""
) {
$podcasts = $helper->getContent(Content::PODCAST, $content->getSlug(), "published", "desc", 0, 0, true, "*", true)["content"];
$images = [];
foreach($podcasts as $c) {
$cm = $c->getContentMetaByKey("podcast_image");
if(is_null($cm) || $cm->getMetavalue() == 0) {
$images[] = "";
}
else {
$m = $mediaHelper->getMediaByOldId($cm->getMetavalue());
$images[] = $m;
}
}
return $this->defaultRender("content/tmpl/podcasts.html.twig", [
"content" => $content,
"podcasts" => $podcasts,
"images" => $images,
"meta" => ["adGroup" => "rlw"],
]);
}
/**
* @Route("/post/{slug}", name="post_master")
*/
public function post(
Request $request,
ContentHelper $contentHelper,
$slug = ""
) {
/*if($this->site_code == Content::SITE_CCS && (!$this->user || (!$this->user->isMember() && !$this->user->isAdmin()))) {
return $this->redirectToRoute("sign-in_ccs");
}*/
$post = $contentHelper->getPostBySlug($slug);
$recommendPost = $contentHelper->getRecommendedPosts($post->getCategory() ? $post->getCategory() : (!empty($post->getSecondaryCategories()) ? $post->getSecondaryCategories()[0] : null), 3, $post->getId());
return $this->contentMembersOnlyCheck($post) ??
$this->defaultRender("content/content.html.twig", [
"content" => $post,
"meta" => [
"title" => $post->getTitle(),
"recommended" => $recommendPost,
],
]);
}
/**
* @Route("/gallery/{slug}",name="gallery_master")
*/
public function gallery (
Request $request,
ContentHelper $helper,
$slug
) {
$gallery = $helper->getContentBySlug(Content::GALLERY, $slug);
//TODO: Should we have site specific code here? or override in RCS controller?
$breadcrumbs = [];
if($this->site_code == Content::SITE_RCS) {
$bread_title = "Roofing Galleries";
$bread_href = "/roofing-galleries";
$category = $gallery->getCategory();
if($category && $category->getSlug() == "partner-galleries") {
$bread_title = "Partner Galleries";
$bread_href = "/partner-galleries";
}
$breadcrumbs[] = [
"title" => $bread_title,
"href" => $bread_href,
];
}
$breadcrumbs[] = [
"title" => $gallery->getTitle(),
"href" => "/partner-galleries/{$gallery->getSlug()}",
];
return $this->defaultRender("content/content.html.twig", [
"content" => $gallery,
"pagenum" => 1,
"meta" => [
"title" => $gallery->getTitle(),
"breadcrumbs" => $breadcrumbs
]
]);
}
/**
* @Route("/podcast/{slug}", name="podcast_master")
*/
public function podcast (
Request $request,
ContentHelper $helper,
$slug = ""
) {
$podcast = $helper->getContentBySlug(Content::PODCAST, $slug);
$primaryCategory = $podcast->getCategory();
$categories = $podcast->getSecondaryCategories();
$breadcrumbs = [];
$parent_breadcrumb = "";
if($primaryCategory && $primaryCategory->getSlug() == "partner-podcast") {
$breadcrumbs[] = [
"title" => "Partner Podcasts",
"href" => "/partner-podcast",
];
}
else {
$breadcrumbs[] = [
"title" => "Podcasts",
"href" => "/podcasts",
];
}
foreach($categories as $category) {
if($category->getTaxonomy() == "rcs-podcast-type") {
$parent_breadcrumb = [
"title" => $category->getTitle(),
"href" => "/podcasts/{$category->getSlug()}",
];
}
}
if($parent_breadcrumb) {
$breadcrumbs[] = $parent_breadcrumb;
}
$breadcrumbs[] = [
"title" => $podcast->getTitle(),
"href" => "/podcast/{$podcast->getSlug()}",
];
return $this->defaultRender("content/content.html.twig", [
"content" => $podcast,
"pagenum" => 1, //< is this needed?
"meta" => array (
"title" => $podcast->getTitle(),
"breadcrumbs" => $breadcrumbs
)
]);
}
/**
* @Route("/webinar/{slug}", name="webinar_master")
*/
public function webinar (
Request $request,
ContentHelper $helper,
$slug = ""
) {
$webinar = $helper->getContentBySlug(Content::WEBINAR, $slug);
return $this->contentMembersOnlyCheck($webinar) ??
$this->defaultRender("content/content.html.twig", [
"content" => $webinar,
"pagenum" => 1,
"meta" => [
"title" => $webinar->getTitle(),
"adgroup" => "rlw"
],
]);
}
/**
* @Route("/promos-rebates/{slug}", name="promos_master")
*/
public function promos (
Request $request,
ContentHelper $contentHelper,
$slug
) {
$promo = $contentHelper->getContentBySlug(Content::PROMOS_REBATES, $slug);
return $this->defaultRender("content/content.html.twig", [
"content" => $promo,
"pagenum" => "",
"meta" => [
"title" => $promo->getTitle(),
"breadcrumbs" => [
[
"title" => "Promos & Rebates", //TODO: rework breadcrumbs?
"href" => "/promos-rebates",
],
[
"title" => $promo->getTitle(),
"href" => "/promo/{$promo->getSlug()}",
],
]
]
]);
}
/**
* @Route("/ebooks/{slug}", name="ebook_master")
*/
public function ebook (
Request $request,
ContentHelper $contentHelper,
$slug
) {
$ebook = $contentHelper->getContentBySlug(Content::EBOOK, $slug);
$ebooksHref = "/ebooks";
if($this->site_code == SiteConfig::SITE_AAR) {
$ebooksHref = "/ebooks-aar";
}
elseif($this->site_code == SiteConfig::SITE_MCS) {
$ebooksHref = "/ebooks-mcs";
}
elseif($this->site_code == SiteConfig::SITE_CCS) {
$ebooksHref = "/ebooks";
}
return $this->defaultRender("content/content.html.twig", [
"content" => $ebook,
"pagenum" => 1,
"meta" => [
"title" => $ebook->getTitle(),
"breadcrumbs" => [
[
"title" => "eBooks",
"href" => $ebooksHref,
],
[
"title" => $ebook->getTitle(),
"href" => "/ebook/{$ebook->getSlug()}",
],
],
]
]);
}
public function ebooks(
Request $request,
ContentHelper $contentHelper,
CategoryHelper $categoryHelper,
CustomerHelper $customerHelper,
$slug,
$content = "",
$customer = ""
) {
if($slug == "partner-ebooks") {
$eBooks = $contentHelper->getEbooks($customer);
$customers = $customerHelper->customerHasEbooks();
return $this->defaultRender("content/tmpl/ebooks.html.twig",[
"slug" => $slug,
"content" => $content,
"customers" => $customers,
"eBooks" => $eBooks,
"meta" => [
"title" => "Partner eBooks",
"breadcrumbs" => [
[
"title" => "Partner eBooks",
"href" => "/partner-ebooks",
]
],
]
]);
}
else {
$eBooks = $contentHelper->getEbooks();
if($this->site_code == SiteConfig::SITE_AAR) {
$categories = $categoryHelper->getPopulatedCategoriesByTaxonomy('aar_ebook-category', $this->site_code);
}
else {
$categories = $categoryHelper->getPopulatedCategoriesByTaxonomy('ebook-category', $this->site_code);
}
foreach($categories as $key => $category) {
if($category->getSlug() == "ebooks-misfits") {
unset($categories[$key]);
}
}
$ebooksHref = "/ebooks";
if($this->site_code == SiteConfig::SITE_AAR) {
$ebooksHref = "/ebooks-aar";
}
elseif($this->site_code == SiteConfig::SITE_MCS) {
$ebooksHref = "/ebooks-mcs";
}
elseif($this->site_code == SiteConfig::SITE_CCS) {
$ebooksHref = "/ebooks-ccs";
}
return $this->defaultRender("content/tmpl/ebooks.html.twig",[
"slug" => $slug,
"content" => $content,
"categories" => $categories,
"eBooks" => $eBooks,
"meta" => [
"title" => "eBooks",
"breadcrumbs" => [
[
"title" => "eBooks",
"href" => $ebooksHref,
]
],
]
]);
}
}
/**
* @Route("/contests-and-games/{slug}",
* requirements={"slug"="^[a-zA-Z0-9\-]+$"},
* name="contests_master"
* )
*/
public function contests (
Request $request,
ContentHelper $contentHelper,
$slug
) {
$contest = $contentHelper->getContentBySlug(Content::CONTEST_GAMES, $slug);
return $this->defaultRender("content/content.html.twig", [
"content" => $contest,
"pagenum" => 1,
"meta" => [
"title" => $contest->getTitle(),
"breadcrumbs" => [
[
"title" => "Contests & Games",
"href" => "/contests-and-games",
],
[
"title" => $contest->getTitle(),
"href" => "/contests-and-games/{$contest->getSlug()}",
]
]
]
]);
}
/**
* @Route("/award/{slug}", name="award_master")
*/
public function award (
Request $request,
ContentHelper $contentHelper,
$slug
) {
$award = $contentHelper->getContentBySlug(Content::AWARD, $slug);
return $this->defaultRender("content/content.html.twig", [
"content" => $award,
"pagenum" => "",
"meta" => array (
"title" => $award->getTitle(),
"breadcrumbs" => array (
array (
"title" => "Awards",
"href" => "/awards",
),
array (
"title" => $award->getTitle(),
"href" => "/award/{$award->getSlug()}",
),
)
)
]);
}
/**
* @Route("/scholarship/{slug}", name="scholarship_master")
*/
public function scholarship (
Request $request,
ContentHelper $contentHelper,
$slug
) {
$scholarship = $contentHelper->getContentBySlug(Content::SCHOLARSHIP, $slug);
return $this->defaultRender("content/content.html.twig", [
"content" => $scholarship,
"pagenum" => "",
"meta" => array (
"title" => $scholarship->getTitle(),
"breadcrumbs" => array (
array (
"title" => "Scholarships",
"href" => "/scholarships",
),
array (
"title" => $scholarship->getTitle(),
"href" => "/scholarship/{$scholarship->getSlug()}",
),
)
)
]);
}
/**
* @Route("/video/{slug}", name="video_master")
*/
public function video (
Request $request,
ContentHelper $contentHelper,
$slug
) {
$video = $contentHelper->getContentBySlug(Content::VIDEO, $slug);
return $this->defaultRender("content/content.html.twig", [
"content" => $video,
"pagenum" => "",
"meta" => array (
"title" => $video->getTitle(),
"breadcrumbs" => array (
array (
"title" => "Videos",
"href" => "/videos",
),
array (
"title" => $video->getTitle(),
"href" => "/video/{$video->getSlug()}",
),
)
)
]);
}
/**
* @Route("/r-club-perk/{slug}", name="r-club-perk_master")
*/
public function rClubPerk (
Request $request,
ContentHelper $contentHelper,
$slug
) {
$perk = $contentHelper->getContentBySlug(Content::R_CLUB_PERK, $slug);
return $this->defaultRender("content/content.html.twig", [
"content" => $perk,
"pagenum" => "",
"meta" => array (
"title" => $perk->getTitle(),
"breadcrumbs" => array (
array (
"title" => "R-Club Perks",
"href" => "/members-only",
),
array (
"title" => $perk->getTitle(),
"href" => "/r-club-perk/{$perk->getSlug()}",
),
)
)
]);
}
/**
* Classified Listing Route
*
* @Route(
* "/our-listings/{page}/{keywords}/{location}/{category}/{areas}",
* defaults={ "page"="_", "keywords"="_", "location"="_", "category"="_", "areas"="_" },
* name="classifiedIndex_master",
* methods={"GET"}
* )
*/
public function classifiedIndex (
Request $request,
ContentHelper $contentHelper,
CategoryHelper $categoryHelper,
$page = "_",
$keywords = "_",
$location = "_",
$category = "_",
$areas = "_"
) {
try {
$pagingSize = 25;
$group = $request->get("c");
if ($group) {
$group = $categoryHelper->getCategoryBySlug($group);
}
$records = $contentHelper->getClassifiedListings($page, $keywords, $location, $category, $areas, $group, $pagingSize);
if(empty($records["listings"])) {
//If no listings are found, try again on the first page. Prevents going past the final page due to pressing multiple buttons at once.
$page = 0;
$records = $contentHelper->getClassifiedListings($page, $keywords, $location, $category, $areas, $group, $pagingSize);
}
$listingCategories = $categoryHelper->getCategoriesByTaxonomy("job_listing_category");
$listingAreas = $categoryHelper->getCategoriesByTaxonomy("job_listing_type");
$dynamic_content = $contentHelper->getStaticPageBySlug("static-rcs-classified-index");
if($dynamic_content) {
$dynamic_content = $dynamic_content->getContentFull();
}
return $this->defaultRender("content/classified-index.html.twig", [
"dynamic_content" => $dynamic_content,
"listings" => $records["listings"],
"totalListings" => $records["total"],
"listingCategories" => $listingCategories,
"listingAreas" => $listingAreas,
"group" => (($group) ? $group->getSlug() : ""),
"page" => $page,
"pagingSize" => $pagingSize,
"keywords" => $keywords == "_" ? "" : $keywords,
"location" => $location == "_" ? "" : $location,
"category" => $category == "_" ? "" : $category,
"areas" => $areas == "_" ? "" : explode("-", $areas),
"meta" => [
"title" => "Our Classified Listings",
"breadcrumbs" => [
[
"title" => "Our Classified Listings",
"href" => "/our-listings" . (($group) ? "?c={$group->getSlug()}" : ""), // make sure to include any sorting categories
]
]
]
]);
} catch (\Exception $e) {
throw $e;
}
}
/**
* @Route("/listing/{slug}", name="classified_master")
*/
public function classified(
Request $request,
ContentHelper $helper,
$slug = ""
) {
$listing = $helper->getClassifiedBySlug($slug);
$meta_collection = $listing->getContentmeta();
$content_meta = array();
foreach($meta_collection as $meta) {
$content_meta[$meta->getMetakey()] = $meta->getMetavalue();
}
$category_collection = $listing->getSecondaryCategories();
$regions = array();
foreach($category_collection as $category) {
if($category->getTaxonomy() == "job_listing_type") {
$regions[] = $category->getTitle();
}
}
if(count($regions) > 1) {
$region = "Multiple";
}
elseif(count($regions) == 1) {
$region = $regions[0];
}
else {
//Should never be empty
$region = "No Region";
}
return $this->defaultRender("content/content.html.twig", [
"content" => $listing,
"content_meta" => $content_meta,
"region" => $region,
"autoplay" => isset($_GET['autoplay']) && $_GET["autoplay"] == 1 ? true : false,
"meta" => [
"title" => "Our Classified Listings",
"breadcrumbs" => [
[
"title" => "Our Classified Listings",
"href" => "/our-listings",
],
[
"title" => $listing->getTitle(),
"href" => "/listing/{$listing->getSlug()}"
]
]
]
]);
}
/**
* @Route(name="classified_request_info", methods={"POST"})
*/
public function classifiedRequestInfo(
Request $request,
ContentHelper $contentHelper,
EmailHelper $emailHelper
) {
$referer = $request->headers->get('referer');
if($emailHelper->checkCaptcha($request->get("g-recaptcha-response"))) {
$l = $request->get("lead");
$lead = new Lead();
$lead->setFirstname($request->get('fname'));
$lead->setLastname($request->get('lname'));
$lead->setEmail($request->get('email'));
$lead->setIpAddress($request->getClientIp());
$lead->setRefUrl($request->headers->get("referer"));
$lead->setUserAgent($request->headers->get("User-Agent"));
$ref_url = $request->headers->get("referer");
if($ref_url) {
$slug = strtok(substr($ref_url, strrpos($ref_url, '/') + 1), '?');
if($slug) {
$content = $contentHelper->getContentBySlugRaw($slug);
$lead->setContent($content);
}
}
$em = $this->getDoctrine()->getManager();
$em->persist($lead);
$em->flush();
$pooled = null;
if($request->get("contact_email")) {
$reply_text = $request->get('fname') ? "Click here to respond to {$request->get('fname')}" : "Click here to reply";
$pooled = $emailHelper->sendEmail(trim($request->get("contact_email")), "New submission from Classified Listing Contact Form", [
["p" => "Hello {$request->get('contact_name')},"],
["p" => "{$request->get('fname')} {$request->get('lname')} ({$request->get('email')}) has replied to your \"{$request->get('listing_title')}\" classified listing with the following message:"],
["p" => "{$request->get('message')}"],
["button" => ["href" => "mailto:{$request->get('email')}", "text" => $reply_text]],
], $request->files);
}
if ($pooled) {
$emailHelper->sendEmail($request->get("email"), "Classified Listing Contact Confirmation", [
["p" => "Thanks for contacting us! We will get in touch with you shortly."],
]);
$this->addFlash("success", "Thanks for contacting us! We will get in touch with you shortly.");
return new RedirectResponse($referer);
/*
The flash message isn't being displayed with this method... and if you opened another page in a different tab, it will mess up last_route.
print_r($session->get("last_route"));
return $this->redirectToRoute($session->get("last_route")["name"], array_merge($session->get("last_route")["params"], ["message" => ["type" => "success", "text" => "Email sent"]]));
*/
}
}
else {
//temp2-5
//$this->addFlash("danger", "The reCAPTCHA was invalid. Please try again.");
return new RedirectResponse($referer);
}
$session = $request->getSession();
$session->getFlashBag()->add('danger', 'There was an error sending your request. Please try again later.');
return new RedirectResponse($referer);
}
//--Directory Start--
/**
* @Route(
* "/our-directory/{page}/{category}/{type}/{search}/{location}/{state}",
* defaults={"page"="", "category"="", "type"="", "search"="", "location"="", "state"=""},
* name="directoryIndex_master",
* methods={"GET"}
* )
*/
public function directoryIndex (
Request $request,
ContentHelper $helper,
$page = "",
$category = "",
$type = "",
$search = "",
$location = "",
$state = ""
) {
$page = (int) $page;
$records = $helper->getDirectoryListings($page, $category, $type, $search, $location, $state);
$categories = $helper->getDirectoryCategories();
$stateOptions = Customer::STATES_PROVINCES;
$search = ($search == "_") ? "" : $search;
$breadcrumbs = [
[
"title" => strtoupper(SiteConfig::CONFIGS[$this->site_code]["site_code"]) . " Directory",
"href" => "/our-directory/",
]
];
return $this->defaultRender("content/directory.html.twig", [
"listings" => $records["listings"],
"total" => $records["total"],
"page" => $page,
"limit" => ContentHelper::DEFAULT_LIMIT,
"search" => $search,
"locations" => $location,
"states" => $state,
"stateOptions" => $stateOptions,
"categories" => $categories,
"category" => $category,
"filters" => $type,
"show_filters" => $request->query->get("filter") !== "0",
"meta" => [
"title" => strtoupper(SiteConfig::CONFIGS[$this->site_code]["site_code"]) . " Directory",
"breadcrumbs" => $breadcrumbs,
]
]);
}
/**
* @Route(
* "/directory/{slug}",
* name="directory_page_master",
* methods={"GET"}
* )
*/
public function directory(
Request $request,
ContentHelper $helper,
CategoryHelper $categoryHelper,
$slug = ""
) {
$directory = $helper->getDirectoryBySlug($slug);
//$customer = $directory->getCustomers()->first();
$customer = $directory->getDirectory();
$level = $customer->getCustomerLevelString($this->site_code);
$types = $customer->getCustomerTypeArray();
// hide or show areas of template
/*
$show_promotions = (
(in_array(Customer::TYPE_DISTRIBUTORS_STRING, $types) && ($level == "Partner" || $level == "Premium" || $level == "Best" || $level == "Better" || $level == "Good")) ||
(in_array(Customer::TYPE_PRODUCTS_SERVICES_STRING, $types) && ($level == "Partner" || $level == "Premium" || $level == "Best" || $level == "Better" || $level == "Good")) ||
(in_array(Customer::TYPE_ASSOCIATIONS_STRING, $types)) ||
(in_array(Customer::TYPE_RCS_PARTNERS_STRING, $types))
);
*/
$show_promotions = $level && $level != "Standard";
// In case we want to break this up more
$show_photos = $show_promotions;
$show_videos = $show_promotions;
$show_education = $show_promotions;
$show_ebooks = $show_promotions;
$show_contestgames = $show_promotions;
$show_awards = $show_promotions;
$show_scholarships = $show_promotions;
$show_upcoming = $show_promotions;
$show_newsletters = $show_promotions;
$show_coffeeblog = $show_promotions;
$show_literature = $show_promotions;
$show_podcasts = $show_promotions;
$show_webinars = $show_promotions;
$show_classifieds = $show_promotions;
$show_buy_online = $show_promotions;
$show_video = $show_promotions;
$show_products = $show_promotions;
//Todo: use content helper function to pull these
//Spanish
try {
$spanishCat = $categoryHelper->getCategoryBySlug("en-espanol")->getId();
}catch(\Exception $e) {
$spanishCat = null;
}
$spanish_content = [];
if($spanishCat) {
$sql = implode(" ", [
"SELECT content",
"FROM",
"App\Entity\Content content",
"JOIN ",
"content.secondary_categories sc",
"LEFT JOIN ",
"content.customers c",
"WHERE",
"sc.id = :id and content.status = 1 and c.id = :cid",
"ORDER BY content.created_at DESC",
]);
$entityManager = $this->getDoctrine()->getManager();
$query = $entityManager->createQuery($sql)
->setParameter(":id", $spanishCat)
->setParameter( ":cid", $customer->getId())
->setFirstResult(0)
->setMaxResults(4);
$spanish_content = $query->getResult();
}
//International
try {
$intCat = $categoryHelper->getCategoryBySlug("international")->getId();
}catch(\Exception $e) {
$intCat = null;
}
$int_content = [];
if($intCat) {
$sql = implode(" ", [
"SELECT content",
"FROM",
"App\Entity\Content content",
"JOIN ",
"content.secondary_categories sc",
"LEFT JOIN ",
"content.customers c",
"WHERE",
"sc.id = :id and content.status = 1 and c.id = :cid",
"ORDER BY content.created_at DESC",
]);
$entityManager = $this->getDoctrine()->getManager();
$query = $entityManager->createQuery($sql)
->setParameter(":id", $intCat)
->setParameter( ":cid", $customer->getId())
->setFirstResult(0)
->setMaxResults(4);
$int_content = $query->getResult();
}
//Canada
try {
$canadaCat = $categoryHelper->getCategoryBySlug("canada")->getId();
}catch(\Exception $e) {
$canadaCat = null;
}
$canada_content = [];
if($canadaCat) {
$sql = implode(" ", [
"SELECT content",
"FROM",
"App\Entity\Content content",
"JOIN ",
"content.secondary_categories sc",
"LEFT JOIN ",
"content.customers c",
"WHERE",
"sc.id = :id and content.status = 1 and c.id = :cid",
"ORDER BY content.created_at DESC",
]);
$entityManager = $this->getDoctrine()->getManager();
$query = $entityManager->createQuery($sql)
->setParameter(":id", $canadaCat)
->setParameter( ":cid", $customer->getId())
->setFirstResult(0)
->setMaxResults(4);
$canada_content = $query->getResult();
}
// Whether to hide the footer ad - should this be used?
//$hide_ad = $row["level"] != "Standard";
$breadcrumbs = [
[
"title" => strtoupper(SiteConfig::CONFIGS[$this->site_code]["site_code"]) . " Directory",
"href" => "/our-directory/",
],
[
"title" => $directory->getTitle(),
"href" => "/directory/{$directory->getSlug()}",
]
];
return $this->defaultRender("content/content.html.twig", [
"content" => $directory,
"customer" => $customer,
"show_promotions" => $show_promotions,
"show_photos" => $show_photos,
"show_videos" => $show_videos,
"show_education" => $show_education,
"show_ebooks" => $show_ebooks,
"show_contestgames" => $show_contestgames,
"show_awards" => $show_awards,
"show_scholarships" => $show_scholarships,
"show_upcoming" => $show_upcoming,
"show_newsletters" => $show_newsletters,
"show_coffeeblog" => $show_coffeeblog,
"show_literature" => $show_literature,
"show_podcasts" => $show_podcasts,
"show_webinars" => $show_webinars,
"show_classifieds" => $show_classifieds,
"show_buy_online" => $show_buy_online,
"show_products" => $show_products,
"show_video" => $show_video,
"buy_online_posts" => $helper->getPaginatedContentByType(Content::POST, 4, 1, "", $customer, "buy-online", false),
"video_posts" => $helper->getPaginatedContentByType(Content::POST, 3, 1, "", $customer, "partner-videos", false),
"latest_news" => $helper->getPaginatedContentByType(Content::POST, 3, 1, "", $customer, "newsroom", false),
"upcoming_events" => $helper->getPaginatedContentByType(Content::EVENT, 3, 1, "", $customer, "", false),
"lunch_and_learn" => $helper->getPaginatedContentByType(Content::WEBINAR, 3, 1, "", $customer, "on-demand-lunch-learn", false),
"webinars" => $helper->getPaginatedContentByType(Content::WEBINAR, 3, 1, "", $customer, "", false, "on-demand-lunch-learn"),
"spanish_content" => $spanish_content,
"int_content" => $int_content,
"canada_content" => $canada_content,
"email_is_valid" => filter_var($customer->getEmail(), FILTER_VALIDATE_EMAIL),
"meta" => [
"title" => $directory->getTitle(),
"breadcrumbs" => $breadcrumbs,
"root" => "/directory/".$directory->getSlug(),
]
]);
}
/**
* @Route("/directory/{slug}/posts/{page}", name="directory_posts_master")
*/
public function directoryPosts(
Request $request,
ContentHelper $helper,
$slug = "",
$page = 1
) {
$directory = $helper->getDirectoryBySlug($slug);
$customer = $directory->getDirectory();
$length = 10;
$posts = $helper->getPaginatedContentByType(Content::POST, $length, $page, "", $customer, "newsroom", false);
$total = $helper->countPostsByCustomer($customer);
$breadcrumbs = [
[
"title" => strtoupper(SiteConfig::CONFIGS[$this->site_code]["site_code"]) . " Directory",
"href" => "/our-directory/",
],
[
"title" => $directory->getTitle(),
"href" => "/directory/{$directory->getSlug()}",
],
[
"title" => "Posts",
"href" => "/directory/{$directory->getSlug()}/posts",
]
];
return $this->defaultRender("content/post.html.twig", [
"customer" => $customer,
"posts" => $posts,
"total" => $total,
"length" => $length,
"page" => $page,
"meta" => [
"title" => $directory->getTitle(),
"breadcrumbs" => $breadcrumbs,
"root" => "/directory/".$directory->getSlug()."/posts",
]
]);
}
/**
* @Route("/directory/{slug}/content/buy-online/{page}", name="directory_buyonline_content_master")
*/
public function directoryBuyOnlineContent(
Request $request,
ContentHelper $helper,
$slug = "",
$type = "2",
$page = 1
) {
$directory = $helper->getDirectoryBySlug($slug); // get directory from url
//$customer = $directory->getCustomers()->first(); // gets the directory customer
$customer = $directory->getDirectory();
$length = 10; //10 per page
$contents = $helper->getContent(
"*",
"buy-online",
"published",
"desc",
($page - 1),
$length,
true,
"*",
true, //secondary categories
false,
false,
false,
$customer->getId()
);
$total = $contents["total"];
$posts = $contents["content"];
$breadcrumbs = [
[
"title" => strtoupper(SiteConfig::CONFIGS[$this->site_code]["site_code"]) . " Directory",
"href" => "/our-directory/",
],
[
"title" => $directory->getTitle(),
"href" => "/directory/{$directory->getSlug()}",
],
[
"title" => "Buy Online",
"href" => "/directory/{$directory->getSlug()}/buy-online",
]
];
return $this->defaultRender("content/post.html.twig", [
"customer" => $customer,
"posts" => $posts,
"total" => $total,
"length" => $length,
"page" => $page,
"meta" => [
"title" => $directory->getTitle(),
"breadcrumbs" => $breadcrumbs,
"root" => "/directory/".$directory->getSlug()."/content/buy-online",
]
]);
}
//todo: make these types of routes generic
/**
* @Route("/directory/{slug}/content/spanish/{page}", name="directory_spanish_content_master")
*/
public function directorySpanishContent(
Request $request,
ContentHelper $helper,
$slug = "",
$type = "2",
$page = 1
) {
$directory = $helper->getDirectoryBySlug($slug); // get directory from url
//$customer = $directory->getCustomers()->first(); // gets the directory customer
$customer = $directory->getDirectory();
$length = 10; //10 per page
$contents = $helper->getContent(
"*",
"en-espanol",
"published",
"desc",
($page - 1),
$length,
true,
"*",
true, //secondary categories
false,
false,
false,
$customer->getId()
);
$total = $contents["total"];
$posts = $contents["content"];
$breadcrumbs = [
[
"title" => strtoupper(SiteConfig::CONFIGS[$this->site_code]["site_code"]) . " Directory",
"href" => "/our-directory/",
],
[
"title" => $directory->getTitle(),
"href" => "/directory/{$directory->getSlug()}",
],
[
"title" => "Spanish Content",
"href" => "/directory/{$directory->getSlug()}/spanish",
]
];
return $this->defaultRender("content/post.html.twig", [
"customer" => $customer,
"posts" => $posts,
"total" => $total,
"length" => $length,
"page" => $page,
"meta" => [
"title" => $directory->getTitle(),
"breadcrumbs" => $breadcrumbs,
"root" => "/directory/".$directory->getSlug()."/content/spanish",
]
]);
}
/**
* @Route("/directory/{slug}/content/international/{page}", name="directory_international_content_master")
*/
public function directoryInternationalContent(
Request $request,
ContentHelper $helper,
$slug = "",
$type = "2",
$page = 1
) {
$directory = $helper->getDirectoryBySlug($slug); // get directory from url
//$customer = $directory->getCustomers()->first(); // gets the directory customer
$customer = $directory->getDirectory();
$length = 10; //10 per page
$contents = $helper->getContent(
"*",
"international",
"published",
"desc",
($page - 1),
$length,
true,
"*",
true, //secondary categories
false,
false,
false,
$customer->getId()
);
$total = $contents["total"];
$posts = $contents["content"];
$breadcrumbs = [
[
"title" => strtoupper(SiteConfig::CONFIGS[$this->site_code]["site_code"]) . " Directory",
"href" => "/our-directory/",
],
[
"title" => $directory->getTitle(),
"href" => "/directory/{$directory->getSlug()}",
],
[
"title" => "International Content",
"href" => "/directory/{$directory->getSlug()}/international",
]
];
return $this->defaultRender("content/post.html.twig", [
"customer" => $customer,
"posts" => $posts,
"total" => $total,
"length" => $length,
"page" => $page,
"meta" => [
"title" => $directory->getTitle(),
"breadcrumbs" => $breadcrumbs,
"root" => "/directory/".$directory->getSlug()."/content/international",
]
]);
}
/**
* @Route("/directory/{slug}/content/canada/{page}", name="directory_canada_content_master")
*/
public function directoryCanadaContent(
Request $request,
ContentHelper $helper,
$slug = "",
$type = "2",
$page = 1
) {
$directory = $helper->getDirectoryBySlug($slug); // get directory from url
//$customer = $directory->getCustomers()->first(); // gets the directory customer
$customer = $directory->getDirectory();
$length = 10; //10 per page
$contents = $helper->getContent(
"*",
"canada",
"published",
"desc",
($page - 1),
$length,
true,
"*",
true, //secondary categories
false,
false,
false,
$customer->getId()
);
$total = $contents["total"];
$posts = $contents["content"];
$breadcrumbs = [
[
"title" => strtoupper(SiteConfig::CONFIGS[$this->site_code]["site_code"]) . " Directory",
"href" => "/our-directory/",
],
[
"title" => $directory->getTitle(),
"href" => "/directory/{$directory->getSlug()}",
],
[
"title" => "Canada Content",
"href" => "/directory/{$directory->getSlug()}/canada",
]
];
return $this->defaultRender("content/post.html.twig", [
"customer" => $customer,
"posts" => $posts,
"total" => $total,
"length" => $length,
"page" => $page,
"meta" => [
"title" => $directory->getTitle(),
"breadcrumbs" => $breadcrumbs,
"root" => "/directory/".$directory->getSlug()."/content/canada",
]
]);
}
/**
* @Route("/directory/{slug}/content/lunch-and-learn/{page}", name="directory_lunch_and_learn_content_master")
*/
public function directoryLunchAndLearnContent(
Request $request,
ContentHelper $helper,
$slug = "",
$type = "8",
$page = 1
) {
$directory = $helper->getDirectoryBySlug($slug); // get directory from url
//$customer = $directory->getCustomers()->first(); // gets the directory customer
$customer = $directory->getDirectory();
$length = 10; //10 per page
$contents = $helper->getContent(
"*",
"on-demand-lunch-learn",
"published",
"desc",
($page - 1),
$length,
true,
"*",
true, //secondary categories
false,
false,
false,
$customer->getId()
);
$total = $contents["total"];
$posts = $contents["content"];
$breadcrumbs = [
[
"title" => strtoupper(SiteConfig::CONFIGS[$this->site_code]["site_code"]) . " Directory",
"href" => "/our-directory/",
],
[
"title" => $directory->getTitle(),
"href" => "/directory/{$directory->getSlug()}",
],
[
"title" => "Lunch and Learn Content",
"href" => "/directory/{$directory->getSlug()}/lunch-and-learn",
]
];
return $this->defaultRender("content/post.html.twig", [
"customer" => $customer,
"posts" => $posts,
"total" => $total,
"length" => $length,
"page" => $page,
"meta" => [
"title" => $directory->getTitle(),
"breadcrumbs" => $breadcrumbs,
"root" => "/directory/".$directory->getSlug()."/content/lunch-and-learn",
]
]);
}
/**
* @Route("/directory/{slug}/content/{type}/{page}", name="directory_content_master")
*/
public function directoryContent(
Request $request,
ContentHelper $helper,
$slug = "",
$type = 2,
$page = 1
) {
$directory = $helper->getDirectoryBySlug($slug);
//$customer = $directory->getCustomers()->first();
$customer = $directory->getDirectory();
$length = 10;
$posts = $helper->getPaginatedContentByType($type, $length, $page, "", $customer);
$total = $helper->countContentByCustomer($type, $customer);
$breadcrumbs = [
[
"title" => strtoupper(SiteConfig::CONFIGS[$this->site_code]["site_code"]) . " Directory",
"href" => "/our-directory/",
],
[
"title" => $directory->getTitle(),
"href" => "/directory/{$directory->getSlug()}",
],
[
"title" => Content::getTypeTextStatic($type),
"href" => "/directory/{$directory->getSlug()}/content/".$type,
]
];
return $this->defaultRender("content/post.html.twig", [
"customer" => $customer,
"posts" => $posts,
"total" => $total,
"length" => $length,
"page" => $page,
"meta" => [
"title" => $directory->getTitle(),
"breadcrumbs" => $breadcrumbs,
"root" => "/directory/".$directory->getSlug()."/content/".$type,
]
]);
}
/**
* @Route(
* "/directory/{slug}",
* name="directory_lead_master",
* methods={"POST"}
* )
*/
public function directoryPostLead (
Request $request,
ContentHelper $helper,
EmailHelper $emailHelper,
ContentHelper $contentHelper,
$slug = ""
) {
if($emailHelper->checkCaptcha($request->get("g-recaptcha-response"))) {
$firstname = $request->get("firstname");
$lastname = $request->get("lastname");
$email = $request->get("email");
$message = $request->get("comments");
if( $contentHelper->isSpam($message) || $contentHelper->isSpam($email) ) {
//temporarily hiding this
//$this->addFlash("danger", "Invalid characters used.");
return new RedirectResponse($request->headers->get('referer'));
}
// update lead items
$lead = new Lead();
$lead->setFirstname($firstname);
$lead->setLastname($lastname);
$lead->setEmail($email);
$lead->setComments($message);
$lead->setIpAddress($request->getClientIp());
$lead->setRefUrl($request->headers->get("referer"));
$lead->setUserAgent($request->headers->get("User-Agent"));
$content = $contentHelper->getContentBySlugRaw($slug);
$lead->setContent($content);
$em = $this->getDoctrine()->getManager();
$em->persist($lead);
$em->flush();
// send e-mail
$directory = $helper->getDirectoryBySlug($slug);
$customers = $directory->getCustomers();
//$recipients = array ("forms@intradatech.com");
foreach ($customers as $customer) {
$recipients[] = $customer->getEmail();
}
//$recipients = implode(",", $recipients);
$emailHelper->sendEmail(
$recipients,
"Contact Form Received",
[
["p" => "Contact Form Received"],
["table" => [
"First Name" => $firstname,
"Last Name" => $lastname,
"Email Address" => $email,
"Message" => $message,
]],
]
);
$this->addFlash("success", "Thanks for contacting us! We will get in touch with you shortly.");
return new RedirectResponse($request->headers->get('referer'));
}
$this->addFlash("danger", "The reCAPTCHA was invalid. Please try again.");
return new RedirectResponse($request->headers->get('referer'));
// set invalid flag for javascript to show form again...
}
/**
* @Route("/ebooks-by/{slug}", name="customerEbooks_master")
*/
public function customerEBooks(
Request $request,
ContentHelper $contentHelper,
$slug
){
$directory = $contentHelper->getDirectoryBySlug($slug);
$customer = $directory->getDirectory();
// $customer = $directory->getDirectory();
$eBooks = $contentHelper->getEbooks($customer->getId());
return $this->defaultRender("content/tmpl/ebooks-list.html.twig",[
"eBooks" => $eBooks,
"customer" => $customer,
"meta" => [
"title" => $customer->getTitle(),
"breadcrumbs" => [
[
"title" => "Partner eBooks",
"href" => "/partner-ebooks",
],
[
"title" => $customer->getTitle(),
"href" => "/ebooks-by/{$customer->getDirectoryContent()->getSlug()}",
],
],
]
]);
}
//--Directory End--
//--Events Start--
/**
* @Route("/events/month/{month}/{year}", name="events_month_master")
*/
public function events_month(
Request $request,
ContentHelper $helper,
$slug = "",
$month = 0,
$year = 0
) {
if(!$month){$month = date("n");}
if(!$year){$year = date("Y");}
$date = date("Y-m-d", strtotime("$year-$month-01"));
$p_month = date("Y-m-d", strtotime("-1 month", strtotime($date)));
$n_month = date("Y-m-d", strtotime("+1 month", strtotime($date)));
return $this->defaultRender("content/tmpl/event-month.html.twig", [
"meta" => [
"title" => "Events",
],
"events_by_day" => $helper->getEventsByMonth($month, $year),
"month" => $month,
"year" => $year,
"date" => $date,
"previous_month" => $p_month,
"next_month" => $n_month,
]);
}
/**
* @Route("/events/day/{month}/{day}/{year}/{search}", name="events_day_master")
*/
public function events_day(
Request $request,
ContentHelper $helper,
$slug = "",
$day = 0,
$month = 0,
$year = 0,
$search = ""
) {
if(!$day){$day = date("j");}
if(!$month){$month = date("n");}
if(!$year){$year = date("Y");}
$date = date("Y-m-d", strtotime("$year-$month-$day"));
$p_day = date("Y-m-d", strtotime("-1 day", strtotime($date)));
$n_day = date("Y-m-d", strtotime("+1 day", strtotime($date)));
$events = $helper->getEventsByDay($date, $search);
$events_meta = array();
foreach($events as $event) {
$meta_collection = $event->getContentmeta();
$content_meta = array();
foreach($meta_collection as $meta) {
$content_meta[$meta->getMetakey()] = $meta->getMetavalue();
}
$events_meta[$event->getId()] = $content_meta;
}
return $this->defaultRender("content/tmpl/event-day.html.twig", [
"meta" => [
"title" => "Events",
],
"events" => $events,
"date" => $date,
"previous_day" => $p_day,
"next_day" => $n_day,
"events_meta" => $events_meta,
"search" => $search,
]);
}
/**
* @Route("/events/{page}/{search}", name="events_master")
*/
public function events(
Request $request,
ContentHelper $helper,
$slug = "",
$page = 1,
$search = ""
) {
$limit = ContentHelper::DEFAULT_LIMIT;
if($request->request->has("eventSearch")) {
$search = $request->request->get("eventSearch");
}
if($request->request->has("eventDate")) {
$date = $request->request->get("eventDate");
if(strtotime($date)) {
$date = date("m/d/Y", strtotime($date));
return $this->redirectToRoute("events_day_master", [
"day" => date("d", strtotime($date)),
"month" => date("m", strtotime($date)),
"year" => date("Y", strtotime($date)),
"search" => $search
]);
}
else {
$date = "";
}
}
if($search) {
$events = $helper->getPaginatedContentByType(Content::EVENT, $limit, $page, $search);
}
else {
$events = $helper->getPaginatedContentByType(Content::EVENT, $limit, $page);
}
if($page == 0) {$page = 1;}
if($page == 1) {
$p_page = -1;
}
else {
$p_page = $page - 1;
}
if($page == -1) {
$n_page = 1;
}
else {
$n_page = $page + 1;
}
if($page < 0 && abs($p_page) > ceil($helper->countPreviousEvents($search) / $limit)) {
$p_page = 0;
}
if($page > 0 && $n_page > ceil($helper->countUpcomingEvents($search) / $limit)) {
$n_page = 0;
}
$events_meta = array();
foreach($events as $event) {
$meta_collection = $event->getContentmeta();
$content_meta = array();
foreach($meta_collection as $meta) {
$content_meta[$meta->getMetakey()] = $meta->getMetavalue();
}
$events_meta[$event->getId()] = $content_meta;
}
return $this->defaultRender("content/tmpl/event-list.html.twig", [
"meta" => [
"title" => "Events",
],
"events" => $events,
"pagenum" => $page,
"previous_pagenum" => $p_page,
"next_pagenum" => $n_page,
"events_meta" => $events_meta,
"search" => $search,
]);
}
/**
* @Route("/event/{slug}", name="event_master")
*/
public function event(
Request $request,
ContentHelper $helper,
$slug = ""
) {
$event = $helper->getEventBySlug($slug);
$meta_collection = $event->getContentmeta();
$content_meta = array();
foreach($meta_collection as $meta) {
$content_meta[$meta->getMetakey()] = $meta->getMetavalue();
}
return $this->defaultRender("content/tmpl/event-single.html.twig", [
"meta" => [
"title" => $event->getTitle(),
],
"content" => $event,
"content_meta" => $content_meta,
"previous_event" => $helper->getPreviousEvent($event),
"next_event" => $helper->getNextEvent($event),
]);
}
/**
* @Route("/download-ics", name="download_ics_file")
**/
public function downloadICSFileAction(
Request $request,
ContentHelper $helper
){
//if ($request->request->has("date_start")) {
$ics_file = $helper->make_ics_file($request->request->get("location"), $request->request->get("description"), $request->request->get("dtstart"),
$request->request->get("dtend"), $request->request->get("summary"), $request->request->get("url"));
//}
$filename = 'rooferscoffeshop-event.ics';
$response = new Response($ics_file);
$disposition = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
$filename
);
$response->headers->set('Content-Disposition', $disposition);
return $response;
}
//--Events End
//--Forums Start--
/**
* @Route("/forum", name="forums_master")
*/
public function forums(
Request $request,
ContentHelper $contentHelper,
$slug = ""
) {
$forums = array();
foreach($contentHelper->getContentByType(Content::FORUM) as $forum) {
$counts = $contentHelper->countTopicsPostsByForum($forum->getSlug());
$topics = $contentHelper->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);
return $this->defaultRender("content/forums-page.html.twig", [
"meta" => [
"title" => "Forums Archive",
"breadcrumbs" => [
[
"title" => "Our Forums",
"href" => "/forum",
]
]
],
"forums" => $forums,
]);
}
/**
* @Route("/forum/topic/{slug}/edit", name="forum_topic_edit_master")
*/
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($this->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_master", ["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_master", ["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_master", ["slug" => $topic->getSlug(), "page" => "1"]);
}
/**
* @Route("/forum/topic/{slug}/delete", name="forum_topic_delete_master")
*/
public function forumTopicDelete(
Request $request,
ContentHelper $helper,
$slug = ""
) {
$topic = $helper->getTopicBySlug($slug);
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$user = $this->getUser();
if($user) {
if($this->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_master", ["slug" => $topic->getPrnt()->getSlug(), "page" => "1"]);
}
}
}
}
/**
* @Route("/forum/topic/{slug}/unsubscribe/{userid}", name="forum_topic_unsubscribe_master")
*/
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_master", ["slug" => $topic->getPrnt()->getSlug(), "page" => "1"]);
}
/**
* @Route("/forum/topic/{slug}/spam", name="forum_topic_spam_master")
*/
public function forumTopicSpam(
Request $request,
ContentHelper $helper,
$slug = ""
) {
$topic = $helper->getTopicBySlug($slug);
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$user = $this->getUser();
if($user) {
if($this->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_master", ["slug" => $topic->getPrnt()->getSlug(), "page" => "1"]);
}
}
}
}
/**
* @Route("/forum/topic/{slug}/{page}", name="forum_topic_master")
*/
public function forumTopic(
Request $request,
ContentHelper $helper,
EmailHelper $emailHelper,
$slug = "",
$page = 1
) {
$topic = $helper->getTopicBySlug($slug);
$limit = ContentHelper::FORUM_LIMIT;
$forum = $topic->getPrnt();
//Members only check
/*if($forum && $forum->getMembersOnly() && (!$this->user || (!$this->user->isMember() && !$this->user->isAdmin()))) {
$this->addFlash("warning", "This forum is only accessible to RCS Club members. Continue below to become a member and access this forum.");
return $this->redirectToRoute("rcs-club-sign-up");
}*/
if($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
//if ($form->isSubmitted() && $form->isValid()) {
if ($request->request->has("reply-content")) {
$content = new Content();
$entityManager = $this->getDoctrine()->getManager();
$site = $entityManager //TODO: test, add to default controller?
->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);
}
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($this->site_code)}\">\"{$topic->getTitle()}\"</a> with the following reply:"],
["p" => "{$content->getContentFull()}"],
//["a" => ["href" => "dev.askaroofer.com/forum/topic/{$topic->getSlug()}/unsubscribe/{$topic->getAuthor()->getId()}", "text" => "Click Here to stop receiving these notifications"]],
["a" => ["href" => "{$topic->getFullURL($this->site_code)}/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($this->site_code)}\">\"{$topic->getTitle()}\"</a> with the following reply:"],
["p" => "{$content->getContentFull()}"],
//["a" => ["href" => "dev.askaroofer.com/forum/topic/{$topic->getSlug()}/unsubscribe/{$notify_user->getId()}", "text" => "Click Here to stop receiving these notifications"]],
["a" => ["href" => "{$topic->getFullURL($this->site_code)}/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->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, true),
"limit" => $limit,
"pagenum" => $page,
"totalcount" => $count,
"totalpages" => ceil($count / $limit),
"baseurl" => $this->generateUrl('forum_topic_master', ['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_master")
*/
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 || $this->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_master", ["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_master", ["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_master", ["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_master",
* methods={"GET"}
* )
*/
public function forumSearch(
Request $request,
ContentHelper $helper,
$search = "",
$page = 1
) {
$limit = ContentHelper::FORUM_LIMIT;
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" => $helper->countForumSearchResults($search),
"totalpages" => ceil($helper->countForumSearchResults($search) / $limit),
"baseurl" => $this->generateUrl('forum_search_master', ['search' => $search]),
]);
}
/**
* @Route("/forum/{slug}/{page}", name="forum_master")
*/
public function forum(
Request $request,
ContentHelper $helper,
UserHelper $userhelper,
EmailHelper $emailHelper,
$slug = "",
$page = 1
) {
$forum = $helper->getForumBySlug($slug);
$limit = ContentHelper::FORUM_LIMIT;
//Members only check
/*if($forum->getMembersOnly() && (!$this->user || (!$this->user->isMember() && !$this->user->isAdmin()))) {
$this->addFlash("warning", "This forum is only accessible to RCS Club members. Continue below to become a member and access this forum.");
return $this->redirectToRoute("rcs-club-sign-up");
}*/
//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(), "", $this->site_code));
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.");
//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" => "askaroofer.com/account", "text" => "Update your membership notification setting here to stop receiving these notifications"]],
]);
}
}
}
*/
//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->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_master', ['slug' => $slug]),
//"form" => $form->createView(),
//"unrestricted" => isset($unrestricted) ? $unrestricted : "", //if the user can post unrestricted HTML content
"unrestricted" => true,
]);
}
/* End Forums */
/**
* @route("/rlw/{slug}",
* name="rlw-posts_master",
* defaults={"slug": ""}
* )
*
*/
public function showRLWPage (
Request $request,
ContentHelper $contentHelper,
$slug = ""
) {
try {
if (!$slug || is_numeric($slug)) {
// show all rlw content...
$page = 1;
$limit = 10;
if (is_numeric($slug)) {
$page = $slug;
}
$data = $contentHelper->getContent(
Content::THE_HUB,
"*",
"created",
"desc",
$page - 1,
$limit
);
$category = [
"title" => "Read Listen Watch - All Learning Resources<span id=\"spacer\"></span>",
"href" => "/rlw",
];
return $this->defaultRender("content/post.html.twig", array (
"posts" => $data["content"],
"total" => $data["total"],
"length" => $limit,
"page" => $page,
"category" => $category,
"meta" => array (
"root" => "/rlw",
"breadcrumbs" => [
[
"title" => "Learn Your Way",
"href" => "/read-listen-watch",
],
[
"title" => "Read Listen Watch - All Learning Resources",
"href" => "/rlw",
]
]
)
));
}
else {
$content = $contentHelper->getContentBySlug(Content::THE_HUB, $slug);
return $this->defaultRender("content/page.html.twig", [
"content" => $content,
"meta" => [
"title" => $content->getTitle(),
"breadcrumbs" => [
[
"title" => "Learn Your Way",
"href" => "/read-listen-watch",
],
[
"title" => $content->getTitle(),
"href" => $content->getURL(),
]
]
],
]);
}
}
catch (Exception $e) {
throw $e;
}
}
/**
* @Route("/thank-you/{slug}", name="thank-you-landing-page_master")
*
*/
public function showThankYouPage (
ContentHelper $contentHelper,
Request $request,
$slug
) {
//Thank you landing page
try {
$page = $contentHelper->getThankYouPageBySlug($slug);
return $this->defaultRender("content/thank-you-landing-page.html.twig", [
"page" => $page,
"meta" => [
"title" => $page->getTitle(),
],
]);
}
catch (ResourceNotFoundException $e) {
}
return $this->defaultRender("errors/404.html.twig", [
]);
}
// requires a content object to be passed as $content
public function comment(
Request $request,
ContentHelper $helper,
EmailHelper $emailHelper,
RequestStack $requestStack,
$content = ""
) {
//$limit = ContentHelper::DEFAULT_LIMIT;
//The below code for handling comment submissions stopped working in Symfony 6
//Comment submissions are now handled by the submitCommentAjaxAction function.
/*
//Because this is used as an embedded controller, it receives a sub-request instead of the master request (that has the form submission data).
//This line will set the request to the master request to allow it to be processed.
$request = $requestStack->getCurrentRequest();
$comment = new Comment();
$comment->setContent($content);
if ($request->request->has("comment-text")) {
$comment->setApproved(0);
$comment->setAuthorIP($_SERVER['REMOTE_ADDR']);
$comment->setAgent($_SERVER['HTTP_USER_AGENT']);
$comment->setCommentText($request->request->get("comment-text"));
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$user = $this->getUser();
if($user->getRole() == 8) {
$comment->setApproved(1);
}
$comment->setUser($user);
$comment->setAuthor($user->getDisplayname());
$comment->setAuthorEmail($user->getEmail());
$comment->setApproved(1); //Change 3/25/21 to auto-approve per Heidi
}
else {
$comment->setAuthor($request->request->get("author"));
$comment->setAuthorEmail($request->request->get("email"));
$comment->setAuthorUrl($request->request->get("url"));
}
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($comment);
$entityManager->flush();
$contentType = strtolower($content->getTypeText());
$emailHelper->sendEmail(
["rcs@rooferscoffeeshop.com"],
"New Comment Added - {$content->getTitle()}",
[
["p" => "A new comment has been added to the {$contentType} \"{$content->getTitle()}\"."],
["p" => "User \"{$comment->getAuthor()}\" commented: \"{$comment->getCommentText()}\"."],
["button" => [
"text" => "View Content",
"href" => "{$content->getFullURL($this->site_code)}",
]],
]
);
}
*/
return $this->defaultRender("forms/comment.html.twig", [
"comments" => $helper->getComments($content),
"content" => $content
]);
}
/**
* @Route("/search/{page}",
* name="search_master",
* defaults={"page": 1}
* )
*/
public function search (
Request $request,
ContentHelper $contentHelper,
$page = 1
) {
$search = $request->get("s");
$data = $contentHelper->search($search, $page);
return $this->defaultRender("content/search.html.twig", [
"total" => $data["count"],
"limit" => 15,
"results" => $data["content"],
"page" => $page,
"search" => $search,
"meta" => [
"title" => "Search Results for {$search}",
]
]);
}
// requires a content object to be passed as $content
public function partnerspage(
Request $request,
ContentHelper $contentHelper,
$content = ""
) {
$directories = $contentHelper->getDirectoryListings(0,"_","_","_","_","_",10000);
return $this->defaultRender("content/tmpl/partners-page.html.twig", [
"content" => $content,
"directories" => $directories["listings"],
]);
}
// requires a content object to be passed as $content
public function popoutAd(
Request $request,
ContentHelper $contentHelper,
CustomerHelper $customerHelper,
EmailHelper $emailHelper,
MediaHelper $mediaHelper,
$content = ""
) {
if($content instanceof Content) {
$customer = $content->getPrimaryCustomer();
$popout = $mediaHelper->getPopoutAdByCustomer($customer);
if(!$popout) {
$popout = $mediaHelper->getDefaultPopoutAd();
$customer = $customerHelper->getCustomerById(110);
}
}
else {
//$content = ""; $customer = ""; $popout = "";
$content = "";
$popout = $mediaHelper->getDefaultPopoutAd();
$customer = $customerHelper->getCustomerById(110);
}
return $this->defaultRender("elements/popout-ad.html.twig", [
"popout" => $popout,
"customer" => $customer,
]);
}
// requires a content object to be passed as $content
public function pinnedSidebarAd(
Request $request,
MediaHelper $mediaHelper,
$base_url = "",
$uri = "",
$current_route = ""
) {
//$site_code = $this->site_code;
$ad = $mediaHelper->getPinnedAdByPosition($base_url, parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH), $current_route, "ad-sidebar");
return $this->defaultRender("elements/sidebar-ad.html.twig", [
"ad" => $ad
//,"uri" => parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH)
]);
}
// requires a content object to be passed as $content
public function pinnedCurtainAd(
Request $request,
MediaHelper $mediaHelper,
$base_url = "",
$uri = "",
$current_route = ""
) {
$ad = $mediaHelper->getPinnedAdByPosition($base_url, parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH), $current_route, "ad-curtain");
//Temporarily hard-coding to remove specific ad from specific page per ticket #186003
if($ad && $ad->getId() == 13296 && str_starts_with($uri, "/webinar/maximizing-solar-rooftop-durability")) {
$ad = "";
}
return $this->defaultRender("elements/curtain-ad.html.twig", [
"ad" => $ad
]);
}
/**
* @Route("/quiz/{slug}", name="Quick Quiz")
*/
public function getQuiz(
Request $request,
QuizHelper $quizHelper,
$slug
){
$cookies = $request->cookies;
if (!$this->user && !$cookies->has("$slug-quizToken")) {
$nt = uniqid();
setcookie("$slug-quizToken", $nt,0,'','',true,true);
}
$quiz = $quizHelper->getLandingPageBySlug($slug);
//Static quiz templates:
if ($quiz && in_array($slug, ["wdyfir", "certainteed"]) && $this->site_code == Site::SITE_RCS) {
return $this->defaultRender("content/quiz/$slug/landing.html.twig",$quiz);
}
else {
//Dynamic Quizzes:
$quiz = $quizHelper->getQuizObjectBySlug($slug);
if($quiz) {
return $this->defaultRender("content/quiz/dynamic/landing.html.twig", [
"quiz" => $quiz
]);
}
}
}
/**
* @Route("/quizExport/{quizId}", name="quiz_export")
*/
public function quizExport(
Request $request,
QuizHelper $quizHelper,
$quizId = ""
) {
$access = false;
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$user = $this->getUser();
if($user) {
if($this->user->isAdmin()) {
$access = true;
}
}
}
if(!$access) {
return $this->defaultRender("errors/404.html.twig", []);
}
$quiz = $quizHelper->getQuizById($quizId);
$responses = $quiz->getQuizResponses()->matching(Criteria::create()->orderBy(["datetaken" => Criteria::DESC]));
$questions = $quiz->getQuizQuestions()->matching(Criteria::create()->orderBy(["sort" => Criteria::ASC]));
//Export / Spreadsheet
$spreadsheet = new Spreadsheet();
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
//Sheet 1
$rowNum = 1;
$sheet->setTitle("Quiz Results");
$sheet->setCellValue("A{$rowNum}", "Date Taken");
$sheet->setCellValue("B{$rowNum}", "Name");
$sheet->setCellValue("C{$rowNum}", "Email");
$sheet->setCellValue("D{$rowNum}", "Finished");
$sheet->setCellValue("E{$rowNum}", "Score");
$colVal = "F";
foreach($questions as $question) {
$sheet->setCellValue("{$colVal}{$rowNum}", $question->getTitle());
$colVal++;
}
$sheet->getStyle("A1:{$colVal}1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFDDDDDD');
$rowNum++;
foreach($responses as $response) {
if($questions->first() && !$response->getAnswerByQuestionId($questions->first()->getId())) {
continue; //Skip if first question isn't answered (caused by a bug)
}
$colVal = "A";
$name = $response->getUser() ? $response->getUser()->getFullName() : $response->getNlFullName();
$email = $response->getUser() ? $response->getUser()->getEmail() : $response->getNlEmail();
$sheet->setCellValue("{$colVal}{$rowNum}", $response->getDatetaken()->format("Y-m-d H:i:s")); $colVal++;
$sheet->setCellValue("{$colVal}{$rowNum}", $name); $colVal++;
$sheet->setCellValue("{$colVal}{$rowNum}", $email); $colVal++;
$sheet->setCellValue("{$colVal}{$rowNum}", $response->getIsFinished() ? "Yes" : "No"); $colVal++;
//$sheet->setCellValue("{$colVal}{$rowNum}", $response->getMessage() ? $response->getMessage() : "N/A"); $colVal++;
$sheet->setCellValue("{$colVal}{$rowNum}", $response->getScore()); $colVal++;
foreach($questions as $question) {
$answer = $response->getAnswerByQuestionId($question->getId());
$sheet->setCellValue("{$colVal}{$rowNum}", $answer ? $answer : "");
$colVal++;
}
$rowNum++;
}
foreach(range("A",$sheet->getHighestColumn()) as $columnID) {
$sheet->getColumnDimension($columnID)
->setAutoSize(true);
}
//Finish and save
//$spreadsheet->setActiveSheetIndexByName("Quiz Results");
$writer = new Xlsx($spreadsheet);
$filename = "Quiz Export - {$quiz->getTitle()}.xlsx";
$writer->save("../var/reports/quizzes/{$filename}");
$response = new BinaryFileResponse("../var/reports/quizzes/{$filename}");
$disposition = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
$filename
);
$response->headers->set('Content-Disposition', $disposition);
return $response;
}
/**
* @Route("/quiz/{slug}/collect-information", name="Quiz-Lead",methods={"GET"})
*/
public function quizLead(
Request $request,
QuizHelper $quizHelper,
$slug
){
$quiz = $quizHelper->getQuizObjectBySlug($slug);
$ref = $request->query->get("ref");
if (in_array($slug, ["wdyfir", "certainteed"])) {
return $this->defaultRender("content/quiz/$slug/infoCollector.html.twig", [
'ref'=>$ref,
'img'=>$quizHelper->getLandingPageBySlug($slug)['img']
]);
}
return $this->defaultRender("content/quiz/dynamic/infoCollector.html.twig", [
'ref' => $ref,
'quiz' => $quiz,
//'img'=>$quizHelper->getLandingPageBySlug($slug)['img']
]);
}
/**
* @Route("/quiz/{slug}/collect-information", name="Quiz-Lead-data", methods={"POST"})
*/
public function quizLeadData(
Request $request,
QuizHelper $quizHelper,
$slug
){
$ref = $request->request->get("ref");
$fname = $request->request->get("firstName");
$lname = $request->request->get("lastName");
$email = $request->request->get("email");
$newsletter = $request->request->get("newsletter");
// normalize newsletter
if($newsletter == "on") {
$newsletter = 1;
}else{
$newsletter = 0;
}
// process information // save the lead
$quizHelper->saveUnauthedQuizLead($fname, $lname, $email, $ref, $newsletter);
$quizResponse = $quizHelper->getQuizResponseByRefurl($ref);
$quizHelper->sendQuizResultsEmail($quizResponse->getId());
return $this->redirectToRoute("Quiz-Results", [
"slug" => $slug,
"ref" => $ref
]);
}
/**
* @Route("/quiz/{slug}/{question}", name="Quick-Question", methods={"GET"})
*/
public function getQuestionByQuizByNumber(
Request $request,
QuizHelper $quizHelper,
$slug,
$question
){
$quiz = $quizHelper->getQuizObjectBySlug($slug);
if($quiz->getRequiresLogin() && !$this->user) {
return $this->redirectToRoute("Quick Quiz", [
"slug" => $slug,
]);
}
if (!in_array($slug, ["wdyfir", "certainteed"])) {
$cookies = $request->cookies;
if ($this->user || $cookies->has("$slug-quizToken")) {
$uid = $this->user ? $this->user->getID() : $cookies->get("$slug-quizToken");
$lastQuestionNumber = $quizHelper->getInProgressQuizByID($slug,$uid);
if ($lastQuestionNumber && $lastQuestionNumber+1 != $question) {
return $this->redirectToRoute("Quick-Question", [
"slug" => $slug,
"question" => $lastQuestionNumber+1
]);
}elseif(!$lastQuestionNumber && $question!=1){
return $this->redirectToRoute("Quick-Question", [
"slug" => $slug,
"question" => 1
]);
}
}
}
if (in_array($slug, ["wdyfir", "certainteed"])) {
$q = $quizHelper->getQuestionOptionsByQuizByNumber($slug, $question);
if ($q) {
return $this->defaultRender("content/quiz/$slug/question.html.twig",$q);
}else{
return $this->defaultRender("errors/404.html.twig", []);
}
}
else {
//Dynamic Quizzes:
$number = $question;
$quiz = $quizHelper->getQuizObjectBySlug($slug);
$question = $quiz->getQuestionByNumber($number);
if($question) {
return $this->defaultRender("content/quiz/dynamic/question.html.twig", [
"quiz" => $quiz,
"question" => $question,
"number" => $number
]);
}
}
}
/**
* @Route("/quiz/{slug}/{question}", name="Question-Answer", methods={"POST"})
*/
public function saveQuestionResponse(
Request $request,
QuizHelper $quizHelper,
MailChimpHelper $mailChimpHelper,
$slug,
$question
){
$cookies = $request->cookies;
$qid = $quizHelper->getQuizBySlug($slug)['id'];
if (!$this->user) {
$uid = NULL;
$nt = $cookies->get("$slug-quizToken");
}else{
$uid = $this->user->getID();
$nt = NULL;
}
$questionObject = $quizHelper->getQuestionById($request->request->get("questionId"));
if($questionObject->getType() == QuizQuestion::RADIO_BUTTONS) {
$userAnswer = $quizHelper->getOptionByID($request->request->get("question-$question"));
$qoid = $userAnswer['id'];
$a = $userAnswer['title'];
}
else {
$qoid = null;
$a = $request->request->get("question-$question");
}
$responseID = $quizHelper->saveResponse($uid, $nt, $qid, $questionObject->getId(), $qoid, $a);
$quiz = $quizHelper->getQuizObjectBySlug($slug);
if (in_array($slug, ["wdyfir", "certainteed"]) && $question == $quizHelper->getLastQuestionNumberBySlug($slug)) {
$ref = $quizHelper->finishQuiz($responseID);
if ($this->user) {
$email = $this->user->getEmail();
$fname = $this->user->getFirstName();
$lname = $this->user->getLastName();
// need to add to mailchimp here too
$mailChimpHelper->subscribe($email,
[
'FNAME'=>$fname,
'LNAME'=>$lname
],
[
'WIR'
]
);
$quizHelper->sendQuizResultsEmail($responseID);
return $this->redirectToRoute("Quiz-Results", [
"slug" => $slug,
"ref" => $ref
]);
}else{
return $this->redirectToRoute("Quiz-Lead", [
"slug" => $slug,
"ref" => $ref
]);
}
}
elseif(!in_array($slug, ["wdyfir", "certainteed"]) && $question == $quiz->countQuizQuestions()) {
//Dynamic Quizzes:
$ref = $quizHelper->finishQuiz($responseID);
if ($this->user) {
$quizHelper->sendQuizResultsEmail($responseID, $ref);
return $this->redirectToRoute("Quiz-Results", [
"slug" => $slug,
"ref" => $ref
]);
}
else {
return $this->redirectToRoute("Quiz-Lead", [
"slug" => $slug,
"ref" => $ref
]);
}
}
else{
return $this->redirectToRoute("Quick-Question", [
"slug" => $slug,
"question" => $question+1
]);
}
}
/**
* @Route("/quiz/{slug}/results/{ref}", name="Quiz-Results")
*/
public function quizResults(
Request $request,
QuizHelper $quizHelper,
$slug,
$ref
){
$quiz = $quizHelper->getQuizObjectBySlug($slug);
$results = $quizHelper->getResultsByRef($ref);
if(in_array($slug, ["wdyfir", "certainteed"])) {
return $this->defaultRender("content/quiz/$slug/ending.html.twig", $results);
}
$response = $quizHelper->getQuizResponseByRefurl($ref);
return $this->defaultRender("content/quiz/dynamic/ending.html.twig", [
"quiz" => $quiz,
"response" => $response,
"result" => $response->getQuizResult()
]);
}
/**
* @Route("/quizz/debugger", name="quiz-debugger")
*/
public function quizDebugger(
Request $request,
QuizHelper $quizHelper
){
return new JsonResponse($this->user->getLastname());
}
//TODO: move all ajax to different controllers
/**
* @Route("/ajax/social-data")
*/
public function socialDataAjaxAction(
Request $request,
CustomerHelper $customerHelper
) {
return new JsonResponse(json_encode(
[
"facebookHandles" => $customerHelper->getFacebookHandles(),
"linkedinHandles" => $customerHelper->getLinkedinHandles(),
"twitterHandles" => $customerHelper->getTwitterHandles(),
"tags" => $customerHelper->getCustomerTags()
]
));
}
/**
* @Route("/ajax/link")
*/
public function linkAjaxAction(
Request $request,
MenuHelper $menuHelper,
ContentHelper $contentHelper
) {
if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {
$id = $request->get("id");
$link = $menuHelper->getLinkById($id);
if($link) {
$contentHelper->addImpression($request, "", $link);
return new JsonResponse($link->getRef());
}
}
}
/**
* @Route("/ajax/link-catchall")
*/
public function linkCatchallAjaxAction(
Request $request,
ContentHelper $contentHelper
) {
if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {
$path = $request->get("path");
$href = $request->get("href");
$entityManager = $this->getDoctrine()->getManager();
$content = $entityManager
->getRepository(Content::class)
->getContentByUrl(
$path,
$this->site_code
);
//if($content) {
$contentHelper->addImpression($request, $content, "", "", "3", $href);
return new JsonResponse($content ? $content->getId() : null);
//}
}
}
/**
* @Route("/ajax/mitem-click")
*/
public function mitemClickAjaxAction(
Request $request,
MediaHelper $mediaHelper,
ContentHelper $contentHelper
) {
if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {
$id = $request->get("id");
$item = $mediaHelper->getMediaGroupItemById($id);
if($item) {
$contentHelper->addImpression($request, "", "", $item, 2);
return new JsonResponse($item->getExternalUrl());
}
}
}
/**
* @Route("/ajax/mitem-impression")
*/
public function mitemImpressionAjaxAction(
Request $request,
MediaHelper $mediaHelper,
ContentHelper $contentHelper
) {
if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {
$id = $request->get("id");
$item = $mediaHelper->getMediaGroupItemById($id);
if($item) {
$contentHelper->addImpression($request, "", "", $item, 1);
return new JsonResponse($item->getExternalUrl());
}
}
}
//New function for multiple impressions below
/**
* @Route("/ajax/mitem-impressions")
*/
public function mitemImpressionsAjaxAction(
Request $request,
MediaHelper $mediaHelper,
ContentHelper $contentHelper
) {
if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {
$ids = $request->get("ids");
$return = [];
foreach($ids as $id) {
$item = $mediaHelper->getMediaGroupItemByIdOrNull($id);
if($item) {
$contentHelper->addImpression($request, "", "", $item, 1);
$return[] = $item->getExternalUrl();
}
}
return new JsonResponse($return);
}
}
/**
* @Route("/ajax/content-impressions")
*/
public function contentImpressionsAjaxAction(
Request $request,
ContentHelper $contentHelper
) {
$contentHelper->storeQueuedImpressions($request);
return new JsonResponse("Content Impressions Stored");
}
/**
* @Route("/ajax/like-content")
*/
public function likeAjaxAction(
Request $request,
ContentHelper $helper
) {
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED') && ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1)) {
$id = $request->get("id");
if($id) {
$content = $helper->getContentById($id);
$helper->likeContent($content, $this->getUser());
$likes = $helper->countLikes($content);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($content);
$entityManager->flush();
return new JsonResponse($likes);
}
else {
return null;
}
} else {
}
}
/**
* @Route("/ajax/unlike-content")
*/
public function unlikeAjaxAction(
Request $request,
ContentHelper $helper
) {
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED') && ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1)) {
$id = $request->get("id");
if($id) {
$content = $helper->getContentById($id);
$helper->unlikeContent($content, $this->getUser());
$likes = $helper->countLikes($content);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($content);
$entityManager->flush();
return new JsonResponse($likes);
}
else {
return null;
}
} else {
}
}
/**
* @Route("/ajax/forum-quote-content")
*/
public function forumQuoteAjaxAction(
Request $request,
ContentHelper $helper
) {
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED') && ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1)) {
$id = $request->get("id");
if($id) {
$content = $helper->getContentById($id);
return new JsonResponse("<blockquote>".$content->getContentFull()."<br> -".$content->getAuthor()."</blockquote>");
}
else {
return null;
}
} else {
}
}
/**
* @Route("/ajax/forum-images-upload")
*/
public function forumUploadImage(
Request $request,
ContentHelper $helper
) {
/*
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED') && ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1)) {
$id = $request->get("id");
return new JsonResponse("<blockquote>".$content->getContentFull()."<br> -".$content->getAuthor()."</blockquote>");
}*/
//$accepted_origins = array("http://localhost", "http://192.168.1.1", "http://example.com");
$imageFolder = "uploads/forum/";
reset ($_FILES);
$temp = current($_FILES);
if (is_uploaded_file($temp['tmp_name'])){
// Sanitize input
if (preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $temp['name'])) {
return new JsonResponse(array('error' => "Invalid file name."));
}
// Verify extension
if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png"))) {
return new JsonResponse(array('error' => "Invalid file type."));
}
// Make a unique filename
$filename = pathinfo($temp['name'], PATHINFO_FILENAME );
$ext = pathinfo($temp['name'], PATHINFO_EXTENSION);
$filename = trim(trim(strtolower($filename)), '-');
$filename = str_replace(' ', '-', $filename);
$filename = preg_replace('/-+/', '-', $filename);
$filename = preg_replace('/[^a-z0-9-]/', '', $filename);
$final_filename = $filename . "." . $ext;
$x = 2;
while(file_exists($imageFolder . $final_filename)) {
$final_filename = $filename . '-' . $x++ . "." . $ext;
}
// Accept upload if there was no origin, or if it is an accepted origin
$filetowrite = $imageFolder . $final_filename;
move_uploaded_file($temp['tmp_name'], $filetowrite);
//$filetowrite = $imageFolder . $temp['name'];
//move_uploaded_file($temp['tmp_name'], $filetowrite);
// Respond to the successful upload with JSON.
// Use a location key to specify the path to the saved image resource.
return new JsonResponse(array('location' => "/".$filetowrite));
} else {
// Notify editor that the upload failed
return new JsonResponse(array('error' => "500 Server Error."));
}
}
/**
* @Route("/ajax/ckeditor-image-upload")
*/
public function ckeditorUploadImage(
Request $request,
ContentHelper $helper
) {
if ($request->files->get("upload")) { //image field
$uploaded_image = $request->files->get("upload");
$mime = $uploaded_image->getMimeType();
if(!in_array($mime, ["image/jpg", "image/jpeg", "image/png", "image/gif"])) {
return new JsonResponse(array('error' => "Only PNG, JPG, and GIF file types are allowed."));
}
$media = new Media();
$media->setTitle(pathinfo($uploaded_image->getClientOriginalName(), PATHINFO_FILENAME));
$media->setData($uploaded_image);
$media->setDescription("Image uploaded through CKEditor.");
$media->setName($uploaded_image->getClientOriginalName());
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($media);
$entityManager->flush();
return new JsonResponse(array('url' => $media->getURL()));
} else {
// Notify editor that the upload failed
return new JsonResponse(array('error' => "500 Server Error."));
}
}
/**
* @Route("/ajax/get-user-lead-info")
*/
public function getUserLeadInfoAjaxAction(
Request $request,
ContentHelper $helper
) {
if($this->user && ($this->user->isMember() || $this->user->isAdmin())) {
$lead["firstname"] = $this->user->getUserMetaValueByKey("lead_firstname");
$lead["lastname"] = $this->user->getUserMetaValueByKey("lead_lastname");
$lead["company"] = $this->user->getUserMetaValueByKey("lead_company");
$lead["phone"] = $this->user->getUserMetaValueByKey("lead_phone");
$lead["email"] = $this->user->getUserMetaValueByKey("lead_email");
$lead["address1"] = $this->user->getUserMetaValueByKey("lead_address1");
$lead["address2"] = $this->user->getUserMetaValueByKey("lead_address2");
$lead["city"] = $this->user->getUserMetaValueByKey("lead_city");
$lead["state"] = $this->user->getUserMetaValueByKey("lead_state");
$lead["zip"] = $this->user->getUserMetaValueByKey("lead_zip");
$lead["country"] = $this->user->getUserMetaValueByKey("lead_country");
$lead["country_other"] = $this->user->getUserMetaValueByKey("lead_country_other");
$lead["contractor_type"] = $this->user->getUserMetaValueByKey("lead_contractor_type");
$lead["business_type"] = $this->user->getUserMetaValueByKey("lead_business_type");
return new JsonResponse(json_encode($lead));
} else {
return new JsonResponse("");
}
}
/**
* @Route("/ajax/setSessionVariable")
*/
public function setSessionVariableAjaxAction(
Request $request
) {
if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {
$key = $request->get("key");
$value = $request->get("value");
if($key) {
$session = $request->getSession();
if($value) {
$session->set($key, $value);
}
else {
$session->remove($key);
}
return new JsonResponse("Session variable set.");
}
}
return new JsonResponse("Session variable set.");
}
/**
* @Route("/pollExport/{pollId}", name="poll_export")
*/
public function pollExport(
Request $request,
PollHelper $pollHelper,
$pollId = ""
) {
$access = false;
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$user = $this->getUser();
if($user) {
if($this->user->isAdmin()) {
$access = true;
}
}
}
$poll = $pollHelper->getPollById($pollId);
$pollOptions = $poll->getPollOptions();
$pollResponses = $poll->getPollResponses();
//Export / Spreadsheet
$spreadsheet = new Spreadsheet();
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
//Sheet 1
$rowNum = 1;
$sheet->setTitle("Poll Results");
$sheet->setCellValue("A{$rowNum}", "Poll Option");
$sheet->setCellValue("B{$rowNum}", "Votes");
$sheet->getStyle("A{$rowNum}")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFDDDDDD');
$sheet->getStyle("B{$rowNum}")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFDDDDDD');
$rowNum++;
foreach($pollOptions as $pollOption) {
$sheet->setCellValue("A{$rowNum}", $pollOption->getText());
$sheet->setCellValue("B{$rowNum}", $pollOption->countResponses());
$rowNum++;
}
$sheet->setCellValue("A{$rowNum}", "Total:");
$sheet->setCellValue("B{$rowNum}", $poll->countResponses());
$sheet->getStyle("A{$rowNum}")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFDDDDDD');
$sheet->getStyle("B{$rowNum}")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFDDDDDD');
foreach(range("A",$sheet->getHighestColumn()) as $columnID) {
$sheet->getColumnDimension($columnID)
->setAutoSize(true);
}
//Sheet 2
$indSheet = new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet, 'Individual Votes');
$spreadsheet->addSheet($indSheet, 0);
$rowNum = 1;
$indSheet->setTitle("Individual Votes");
$indSheet->setCellValue("A{$rowNum}", "User");
$indSheet->setCellValue("B{$rowNum}", "Vote");
$indSheet->getStyle("A{$rowNum}")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFDDDDDD');
$indSheet->getStyle("B{$rowNum}")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFDDDDDD');
$rowNum++;
foreach($pollResponses as $pollResponse) {
$indSheet->setCellValue("A{$rowNum}", $pollResponse->getUser() ? $pollResponse->getUser() : "anonymous");
$indSheet->setCellValue("B{$rowNum}", $pollResponse->getPollOption());
$rowNum++;
}
foreach(range("A",$indSheet->getHighestColumn()) as $columnID) {
$indSheet->getColumnDimension($columnID)
->setAutoSize(true);
}
//Finish and save
$spreadsheet->setActiveSheetIndexByName("Poll Results");
$writer = new Xlsx($spreadsheet);
$filename = "Poll Export {$pollId}.xlsx";
$writer->save("../var/reports/polls/{$filename}");
//return new JsonResponse($filename . " saved");
//$filename = $request->request->get("filename");
$response = new BinaryFileResponse("../var/reports/polls/{$filename}");
$disposition = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
$filename
);
$response->headers->set('Content-Disposition', $disposition);
return $response;
}
/**
* @Route("/ajax/pollResponse")
*/
public function addPollResponse(
Request $request,
PollHelper $pollHelper
) {
if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {
$pollId = $request->get("pollId");
$pollOptionId = $request->get("pollOptionId");
$userId = $request->get("userId");
if($pollOptionId) {
$pollHelper->addPollResponse($pollOptionId, $userId ? $userId : NULL);
$results = $pollHelper->getPollResults($pollId);
//$results = implode(" ", $pollHelper->getPollResults($pollId));
return new JsonResponse($results);
}
}
return new JsonResponse("Failure.");
}
/**
* @Route("/ajax/pollResults")
*/
public function getpollResultsAjax(
Request $request,
PollHelper $pollHelper,
Environment $twig,
$id = ""
) {
try {
$id = $request->get("id");
$poll = $pollHelper->getPollById($id);
$tmpl = $twig->load("polls/admin-poll-results-embed.html.twig");
$html = $tmpl->render(
[
"poll" => $poll
]);
return new JsonResponse($html);
}
catch (\Exception $e) {
return new JsonResponse("<div>Error loading poll results.</div>");
//return new JsonResponse($e->getMessage());
}
}
/**
* @Route("/ajax/quizResults")
*/
public function getQuizResultsAjax(
Request $request,
QuizHelper $quizHelper,
Environment $twig,
$id = ""
) {
try {
$id = $request->get("id");
$quiz = $quizHelper->getQuizById($id);
$tmpl = $twig->load("quizzes/admin-quiz-results-embed.html.twig");
$html = $tmpl->render(
[
"quiz" => $quiz
]);
return new JsonResponse($html);
}
catch (\Exception $e) {
return new JsonResponse("<div>Error loading quiz results.</div>");
}
}
/**
* @Route("/ajax/contentUserViews")
*/
public function getContentUserViews(
Request $request,
ContentHelper $contentHelper,
Environment $twig,
$id = ""
) {
//return false;
try {
$id = $request->get("id");
$content = $contentHelper->getContentById($id);
$entityManager = $this->getDoctrine()->getManager();
//TODO: Make a service for this
//Google Analytics
$year = date("Y");
$month = date("n");
//$startDate = date("Y-m-d", strtotime($year."-".$month."-"."01"));
$startDate = date("Y-m-d", strtotime("2020-10-"."01")); //when we started using this custom dimension
//$startDate = new \DateTime($startDate);
$endDate = date("Y-m-t", strtotime($year."-".$month."-01"));
//$endDate = new \DateTime($endDate." 23:59:59");
$client = new \Google_Client();
$client->setApplicationName("RCS Analytic Reports");
$KEY_FILE_LOCATION = __DIR__ . '/../RCS/RCS-AnalyticReports-9cf5364bc460.json';
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics = new \Google_Service_AnalyticsReporting($client);
$dateRange = new \Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate($startDate);
$dateRange->setEndDate($endDate);
$views = new \Google_Service_AnalyticsReporting_Metric();
$views->setExpression("ga:pageviews");
$views->setAlias("pageviews");
$path = new \Google_Service_AnalyticsReporting_Dimension();
$path->setName("ga:pagePath");
$rcsUserID = new \Google_Service_AnalyticsReporting_Dimension();
$rcsUserID->setName("ga:dimension2");
// Create the DimensionFilter.
$dimensionFilter = new \Google_Service_AnalyticsReporting_DimensionFilter();
//Should be faster. Need to set for each job.
$dimensionFilter->setDimensionName('ga:pagePath');
$dimensionFilter->setOperator('IN_LIST');
$dimensionFilter->setExpressions([$content->getURL(1)]);
//$dimensionFilter->setExpressions(["/news-room"]);
// Create the DimensionFilterClauses
$dimensionFilterClause = new \Google_Service_AnalyticsReporting_DimensionFilterClause();
$dimensionFilterClause->setFilters(array($dimensionFilter));
$request = new \Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId("126182454"); //< Unfiltered Website Data
$request->setDateRanges($dateRange);
$request->setDimensions(array($path, $rcsUserID));
$request->setDimensionFilterClauses(array($dimensionFilterClause));
$request->setMetrics(array($views));
$request->setPageSize("10000");
//$request->setPageSize("10");
$order = new \Google_Service_AnalyticsReporting_OrderBy;
$order->setFieldName("ga:pageviews");
$order->setOrderType("VALUE");
$order->setSortOrder("DESCENDING");
$orders[] = $order;
$request->setOrderBys($orders);
$body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests(array($request));
$reports = $analytics->reports->batchGet($body);
$data = [];
for ($reportIndex = 0; $reportIndex < count($reports); $reportIndex++) {
$report = $reports[$reportIndex];
$header = $report->getColumnHeader();
$dimensionHeaders = $header->getDimensions();
$metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
$rows = $report->getData()->getRows();
for ($rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
$row = $rows[$rowIndex];
$dimensions = $row->getDimensions();
$metrics = $row->getMetrics();
$path = "";
$rcsUserID = "";
$count = 0;
for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
if ($dimensionHeaders[$i] == "ga:pagePath") {
$path = $dimensions[$i];
}
if ($dimensionHeaders[$i] == "ga:dimension2") {
$rcsUserID = $dimensions[$i];
}
}
$count = $metrics[0]->getValues()[0];
//strip any url parameters
//$path = strtok($path, "?");
//for ($j = 0; $j < count($metricHeaders) && $j < count($metrics); $j++) {
// $entry = $metricHeaders[$j];
// $values = $metrics[$j];
// for ($valueIndex = 0; $valueIndex < count($values->getValues()); $valueIndex++) {
// $value = $values->getValues()[$valueIndex];
// $count = $value;
// }
//}
//if (!isset($data[$path])) {
// $data[$path] = array();
//}
//if (!isset($data[$path][$rcsUserID])) {
// $data[$path][$rcsUserID] = $count;
//}
//else {
// $data[$path][$rcsUserID] += $count;
//}
if (!isset($data[$rcsUserID])) {
$user = $entityManager
->getRepository(User::class)
->findOneBy(["id" => $rcsUserID]);
$data[$rcsUserID] = ["views" => $count, "user" => $user];
}
}
}
foreach($data as $key => $value) {
/*
if($key == "/") { continue; }
$pos = strrpos($key, '/');
$slug = $pos === false ? $key : substr($key, $pos + 1);
$arr = explode("?", $slug, 2);
$slug = $arr[0];
if(!$slug) { continue; }
$content = $entityManager
->getRepository(Content::class)
->findOneBy(["slug" => $slug]);
if($content) {
$edit_links[$key] = "/admin/content/". $content->getId() . "/edit";
//TODO: Handle switching sites when editing.
//$edit_links[$key] = "/admin/content/". $content->getId() . "/edit?site=". $content->getSite();
}
*/
}
//Just copying above code for single week to get up in time for the meeting. Will clean up later.
$year = date("Y");
$month = date("n");
$day = date("d");
$startDate = date('Y-m-d', strtotime('-1 week'));
$endDate = date("Y-m-d");
$client = new \Google_Client();
$client->setApplicationName("RCS Analytic Reports");
$KEY_FILE_LOCATION = __DIR__ . '/../RCS/RCS-AnalyticReports-9cf5364bc460.json';
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics = new \Google_Service_AnalyticsReporting($client);
$dateRange = new \Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate($startDate);
$dateRange->setEndDate($endDate);
$views = new \Google_Service_AnalyticsReporting_Metric();
$views->setExpression("ga:pageviews");
$views->setAlias("pageviews");
$path = new \Google_Service_AnalyticsReporting_Dimension();
$path->setName("ga:pagePath");
$rcsUserID = new \Google_Service_AnalyticsReporting_Dimension();
$rcsUserID->setName("ga:dimension2");
$dimensionFilter = new \Google_Service_AnalyticsReporting_DimensionFilter();
$dimensionFilter->setDimensionName('ga:pagePath');
$dimensionFilter->setOperator('IN_LIST');
$dimensionFilter->setExpressions([$content->getURL(1)]);
// Create the DimensionFilterClauses
$dimensionFilterClause = new \Google_Service_AnalyticsReporting_DimensionFilterClause();
$dimensionFilterClause->setFilters(array($dimensionFilter));
$request = new \Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId("126182454"); //< Unfiltered Website Data
$request->setDateRanges($dateRange);
$request->setDimensions(array($path, $rcsUserID));
$request->setDimensionFilterClauses(array($dimensionFilterClause));
$request->setMetrics(array($views));
$request->setPageSize("10000");
//$request->setPageSize("10");
$order = new \Google_Service_AnalyticsReporting_OrderBy;
$order->setFieldName("ga:pageviews");
$order->setOrderType("VALUE");
$order->setSortOrder("DESCENDING");
$orders[] = $order;
$request->setOrderBys($orders);
$body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests(array($request));
$reports = $analytics->reports->batchGet($body);
$dataweek = [];
for ($reportIndex = 0; $reportIndex < count($reports); $reportIndex++) {
$report = $reports[$reportIndex];
$header = $report->getColumnHeader();
$dimensionHeaders = $header->getDimensions();
$metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
$rows = $report->getData()->getRows();
for ($rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
$row = $rows[$rowIndex];
$dimensions = $row->getDimensions();
$metrics = $row->getMetrics();
$path = "";
$rcsUserID = "";
$count = 0;
for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
if ($dimensionHeaders[$i] == "ga:pagePath") {
$path = $dimensions[$i];
}
if ($dimensionHeaders[$i] == "ga:dimension2") {
$rcsUserID = $dimensions[$i];
}
}
$count = $metrics[0]->getValues()[0];
if (!isset($dataweek[$rcsUserID])) {
$user = $entityManager
->getRepository(User::class)
->findOneBy(["id" => $rcsUserID]);
$dataweek[$rcsUserID] = ["views" => $count, "user" => $user];
}
}
}
$tmpl = $twig->load("sonata_admin/content-user-views-embed.html.twig");
$html = $tmpl->render(
[
"content" => $content,
"data" => $data,
"dataweek" => $dataweek,
//"rows" => $rows,
]);
return new JsonResponse($html);
}
catch (\Exception $e) {
//return new JsonResponse("<div>Error loading results.</div>");
return new JsonResponse($e->getMessage());
}
}
/**
* @Route("/ajax/accept-cookies")
*/
public function acceptCookiesAjaxAction(
Request $request
) {
if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {
$user = $this->user;
if($user) {
$user->setUsermetum("acceptCookies", "1");
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
return new JsonResponse("1");
}
}
return new JsonResponse("0");
}
/**
* @Route("/ajax/set-preferred-language")
*/
public function preferredLanguageAjaxAction(
Request $request
) {
if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {
$user = $this->user;
$language = $request->get("language");
if($user && $language) {
$contact = $user->getContact();
if($contact) {
$contact->setPreferredLanguage($language);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($contact);
$entityManager->flush();
return new JsonResponse("1");
}
}
}
return new JsonResponse("0");
}
/**
* @Route("/ajax/submit-comment")
*/
public function submitCommentAjaxAction(
Request $request,
MediaHelper $mediaHelper,
ContentHelper $contentHelper,
EmailHelper $emailHelper
) {
if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {
if ($request->get("commentText") && $request->get("contentId")) {
$contentId = $request->get("contentId");
$content = $contentHelper->getContentById($contentId);
$comment = new Comment();
$comment->setContent($content);
$comment->setApproved(0);
$comment->setAuthorIP($_SERVER['REMOTE_ADDR']);
$comment->setAgent($_SERVER['HTTP_USER_AGENT']);
$comment->setCommentText($request->get("commentText"));
if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$user = $this->getUser();
if($user->getRole() == 8) {
$comment->setApproved(1);
}
$comment->setUser($user);
$comment->setAuthor($user->getDisplayname());
$comment->setAuthorEmail($user->getEmail());
$comment->setApproved(1);
}
else {
return false;
//No longer allowing comments from non-logged in users
//$comment->setAuthor($request->request->get("author"));
//$comment->setAuthorEmail($request->request->get("email"));
//$comment->setAuthorUrl($request->request->get("url"));
}
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($comment);
$entityManager->flush();
$contentType = strtolower($content->getTypeText());
$emailHelper->sendEmail(
["rcs@rooferscoffeeshop.com"],
"New Comment Added - {$content->getTitle()}",
[
["p" => "A new comment has been added to the {$contentType} \"{$content->getTitle()}\"."],
["p" => "User \"{$comment->getAuthor()}\" commented: \"{$comment->getCommentText()}\"."],
["button" => [
"text" => "View Content",
"href" => "{$content->getFullURL($this->site_code)}",
]],
]
);
return new JsonResponse(1);
}
}
}
// @Route("/testtesttest", methods={"POST"})
/**
* @Route("/testtesttesths")
*/
public function testtesttesths(
Request $request,
ContentHelper $contentHelper,
CustomerHelper $customerHelper,
HootsuiteHelper $hootsuiteHelper
) {
// get image from post request
// $image = $request->files->get("image");
// $imgObj = [
// "image" => $image->getPathname(),
// "mime" => $image->getMimeType(),
// "size" => $image->getSize(),
// ];
// $respUploadCreate = $hootsuiteHelper->createMediaUploadUri($imgObj);
// $respUploadCreate = json_decode($respUploadCreate, true);
// $respUploadCreate = $respUploadCreate['data'];
// $respUpload = $hootsuiteHelper->uploadMedia($respUploadCreate['uploadUrl'], $imgObj);
// sleep(5); // waiting to be sure that it's ready
// $uploaded = $hootsuiteHelper->confirmMediaUpload($respUploadCreate['id']);
// $resp = [
// "uploadCreate" => $respUploadCreate,
// "upload" => $uploaded,
// ];
//$resp = $hootsuiteHelper->schedulePost("Test post from RCS \n\n\n@AskARooferRCS ", [$respUploadCreate['id']], [125189773], "2025-01-01T12:12:00Z");
//$resp = $hootsuiteHelper->schedulePost("Test post from RCS \n\n\n@AskARooferRCS ", [], [125189773, 7563642], "2025-01-01T12:12:00Z");
return $this->defaultRender("test.html.twig", [
//"data" => json_decode($resp)
"data" => date('Y-m-d H:i:s')
//"data" => date_default_timezone_get()
]);
// $code = "q_muwsc8MGw2zqzDnrn37pj4GcVWYrXCVU5o9fsPr0E.ck04oiLoHqmDPSI5TD0va63-qFf_PYa4WJcZmRpwWK4";
// $resp = $hootsuiteHelper->getMessage(12882399827);
// schedulePost
// $resp = $hootsuiteHelper->getSocialProfiles();
//$hootsuiteHelper->updateSocialProfiles();
// return new JsonResponse(json_encode(print_r($resp)), 200, [], true);
// return new JsonResponse($tokens);
//return new JsonResponse("testtestteset");
}
/**
* @Route("/testtesttestga")
*/
public function testtesttestga(
Request $request,
ContentHelper $contentHelper,
CustomerHelper $customerHelper
) {
return false;
//try {
set_time_limit(600);
/*
$slug = $request->get("slug");
if(!$slug) {
throw new \Exception('Invalid directory.');
}
*/
if($request->request->has("date_start") && $request->request->has("date_end")
&& $request->request->get("date_start") && $request->request->get("date_end")) {
$startDate = date("Y-m-d", strtotime($request->request->get("date_start")));
$startDate = new \DateTime($startDate);
$endDate = date("Y-m-d", strtotime($request->request->get("date_end")));
$endDate = new \DateTime($endDate." 23:59:59");
}
elseif($request->request->has("date_start_current") && $request->request->has("date_end_current")
&& $request->request->get("date_start_current") && $request->request->get("date_end_current")) {
$startDate = date("Y-m-d", strtotime($request->request->get("date_start_current")));
$startDate = new \DateTime($startDate);
$endDate = date("Y-m-d", strtotime($request->request->get("date_end_current")));
$endDate = new \DateTime($endDate." 23:59:59");
}
else {
$year = date("Y");
$month = date("n");
$startDate = date("Y-m-d", strtotime($year."-".$month."-"."01"));
$startDate = new \DateTime($startDate);
$endDate = date("Y-m-t", strtotime($year."-".$month."-"."01"));
$endDate = new \DateTime($endDate." 23:59:59");
}
$data =[];
foreach(SiteConfig::CONFIGS as $site_config) {
if($site_config["id"] != 1/*!isset($site_config["ga_view_id"])*/) {
continue;
}
// 3/14/2019 removing source...
$client = new \Google_Client();
$client->setApplicationName("RCS Analytic Reports");
//$KEY_FILE_LOCATION = __DIR__ . '/My Project-4e8eeee2693a.json';
$KEY_FILE_LOCATION = __DIR__ . '/../RCS/RCS-AnalyticReports-9cf5364bc460.json';
//$KEY_FILE_LOCATION = __DIR__ . '/' . $site_config["analytics_key_file"];
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics = new \Google_Service_AnalyticsReporting($client);
$dateRange = new \Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate($startDate->format('Y-m-d'));
$dateRange->setEndDate($endDate->format('Y-m-d'));
$avgTimeOnPage = new \Google_Service_AnalyticsReporting_Metric();
$avgTimeOnPage->setExpression("ga:avgTimeOnPage");
$avgTimeOnPage->setAlias("avgTimeOnPage");
$path = new \Google_Service_AnalyticsReporting_Dimension();
$path->setName("ga:pagePath");
//$medium = new \Google_Service_AnalyticsReporting_Dimension();
//$medium->setName("ga:medium");
$request = new \Google_Service_AnalyticsReporting_ReportRequest();
//$request->setViewId("126182454"); //< Unfiltered Website Data
$request->setViewId($site_config["ga_view_id"]); //< Unfiltered Website Data
$request->setDateRanges($dateRange);
$request->setDimensions(array($path));
//$request->setDimensions(array($path, $medium));
$request->setMetrics(array($avgTimeOnPage));
$request->setPageSize("10000");
$body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests(array($request));
$reports = $analytics->reports->batchGet($body);
/*
//If we ever have more than 10,000 results, we'll need to filter them or do something like this
// Remove count if you really want everything.
$cnt = 0;
while ($reports->reports[0]->nextPageToken > 0 && $cnt < 10) {
$body->reportRequests[0]->setPageToken($reports->reports[0]->nextPageToken);
$reports = $analytics->reports->batchGet( $body );
$cnt++;
}
*/
// 3/13/2019 removing source
$data[$site_config['id']] = [];
for ($reportIndex = 0; $reportIndex < count($reports); $reportIndex++) {
$report = $reports[$reportIndex];
$header = $report->getColumnHeader();
$dimensionHeaders = $header->getDimensions();
$metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
$rows = $report->getData()->getRows();
for ($rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
$row = $rows[$rowIndex];
$dimensions = $row->getDimensions();
$metrics = $row->getMetrics();
$path = "";
//$medium = "";
$count = 0;
for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
if ($dimensionHeaders[$i] == "ga:pagePath") {
$path = $dimensions[$i];
}
/*if ($dimensionHeaders[$i] == "ga:medium") {
$medium = $dimensions[$i];
}*/
}
//strip any url parameters
$path = strtok($path, "?");
for ($j = 0; $j < count($metricHeaders) && $j < count($metrics); $j++) {
$entry = $metricHeaders[$j];
$values = $metrics[$j];
for ($valueIndex = 0; $valueIndex < count($values->getValues()); $valueIndex++) {
$value = $values->getValues()[$valueIndex];
//$count = $value;
}
}
if (!isset($data[$site_config['id']][$path])) {
$data[$site_config['id']][$path] = (int)$value;
}
/*if (!isset($data[$path]["avgTimeOnPage"])) {
$data[$path]["avgTimeOnPage"] = $value;
}*/
/*if (!isset($data[$path][$medium])) {
$data[$path][$medium] = (int)$count;
}
else {
$data[$path][$medium] += (int)$count;
}*/
}
}
$data[$site_config['id']] = $reports;
//echo "<pre>";var_dump($data);exit;
}
//}
return $this->defaultRender("test.html.twig", [
"data" => $data
]);
//return new JsonResponse(json_encode(print_r($data)), 200, [], true);
}
/**
* @Route("/testtesttestga2")
*/
public function testtesttestga2(
Request $request,
ContentHelper $contentHelper,
CustomerHelper $customerHelper
) {
return false;
/**
* TODO(developer): Replace this variable with your Google Analytics 4
* property ID before running the sample.
*/
//$property_id = 'YOUR-GA4-PROPERTY-ID';
$property_id = '320922983';
// Using a default constructor instructs the client to use the credentials
// specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
//$client = new BetaAnalyticsDataClient();
$KEY_FILE_LOCATION = __DIR__ . '/../RCS/RCS Analytics-70262098a89a.json';
$client = new BetaAnalyticsDataClient([
'credentials' => $KEY_FILE_LOCATION
]);
// Make an API call.
$request = (new RunReportRequest())
->setProperty('properties/' . $property_id)
->setDateRanges([
new DateRange([
'start_date' => '2024-03-31',
'end_date' => 'today',
]),
])
->setDimensions([new Dimension([
'name' => 'city',
]),
])
->setMetrics([new Metric([
'name' => 'activeUsers',
])
]);
$response = $client->runReport($request);
// Print results of an API call.
$print = 'Report result: ' . PHP_EOL;
foreach ($response->getRows() as $row) {
$print .= $row->getDimensionValues()[0]->getValue()
. ' ' . $row->getMetricValues()[0]->getValue() . PHP_EOL;
}
$data = [];
return $this->defaultRender("test.html.twig", [
//"data" => $data
//"data" => $response
"data" => $print
]);
//return new JsonResponse(json_encode(print_r($data)), 200, [], true);
}
/**
* @Route("/testtimeonpage")
*/
public function testtimeonpage(
Request $request,
ContentHelper $contentHelper,
CustomerHelper $customerHelper
) {
return false;
$property_id = '320922983';
$KEY_FILE_LOCATION = __DIR__ . '/../RCS/RCS Analytics-70262098a89a.json';
$client = new BetaAnalyticsDataClient([
'credentials' => $KEY_FILE_LOCATION
]);
// Make an API call.
$request = (new RunReportRequest())
->setProperty('properties/' . $property_id)
->setDateRanges([
new DateRange([
'start_date' => '2024-04-01',
'end_date' => '2024-04-30',
]),
])
->setDimensions([new Dimension([
'name' => 'pagePath',
]),
])
->setMetrics([
new Metric(['name' => 'userEngagementDuration']),
new Metric(['name' => 'activeUsers'])
]);
$response = $client->runReport($request);
// Print results of an API call.
$print = 'Report result: ' . PHP_EOL;
foreach ($response->getRows() as $row) {
$print .= $row->getDimensionValues()[0]->getValue()
//. ' ' . $row->getMetricValues()[0]->getValue() . PHP_EOL;
. ' ' . $row->getMetricValues()[0]->getValue()
. ' ' . $row->getMetricValues()[1]->getValue() . PHP_EOL;
}
//$print = \Doctrine\Common\Util\Debug::dump($response, 4);
$data = [];
return $this->defaultRender("test.html.twig", [
//"data" => $data
//"data" => $response
"data" => $print
]);
//return new JsonResponse(json_encode(print_r($data)), 200, [], true);
}
/**
* @Route("/thecoffeeshops")
*/
public function thecoffeeshops(
Request $request
) {
return false;
return $this->defaultRender("thecoffeeshops.html.twig", [
//"data" => json_decode($resp)
]);
}
}