src/Controller/Master/ContentController.php line 1172

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Master;
  3. use App\Controller\Master\DefaultController as DefaultController;
  4. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  8. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  9. use Symfony\Component\HttpFoundation\RedirectResponse;
  10. use Symfony\Component\HttpFoundation\File\UploadedFile;
  11. use Symfony\Component\HttpFoundation\JsonResponse;
  12. use Symfony\Component\Cache\Adapter\FilesystemAdapter;
  13. use Symfony\Component\Routing\Annotation\Route;
  14. use Symfony\Component\Form\Forms;
  15. use Doctrine\Common\Collections\Criteria;
  16. use App\Form\Type\ContentType;
  17. use App\Form\Type\ContentAdminType;
  18. use App\Form\Type\CommentType;
  19. use App\Entity\Content;
  20. use App\Entity\Site;
  21. use App\Entity\SiteConfig;
  22. use App\Entity\ContentMeta;
  23. use App\Entity\Comment;
  24. use App\Entity\Category;
  25. use App\Entity\Customer;
  26. use App\Entity\CustomerPhone;
  27. use App\Entity\CustomerAddress;
  28. use App\Entity\Lead;
  29. use App\Entity\User;
  30. use App\Entity\Coupon;
  31. use App\Entity\Product;
  32. use App\Entity\Purchase;
  33. use App\Entity\PurchaseItem;
  34. use App\Entity\PurchaseNote;
  35. use App\Entity\Media;
  36. use App\Entity\MediaGroupItem;
  37. use App\Entity\MediaGroup;
  38. use App\Entity\MediaGroupContainer;
  39. use App\Entity\Contact;
  40. use App\Entity\ContentAnalyticsDaily;
  41. use App\Entity\QuizQuestion;
  42. use App\Form\Type\CustomerType;
  43. use App\Form\Type\LeadType;
  44. use App\Form\DirectoryLeadType;
  45. use App\Utils\CategoryHelper;
  46. use App\Utils\ContentHelper;
  47. use App\Utils\CustomerHelper;
  48. use App\Utils\ContactHelper;
  49. use App\Utils\UserHelper;
  50. use App\Utils\EmailHelper;
  51. use App\Utils\OrderHelper;
  52. use App\Utils\MediaHelper;
  53. use App\Utils\MenuHelper;
  54. use App\Utils\LeadHelper;
  55. use App\Utils\PollHelper;
  56. use App\Utils\QuizHelper;
  57. use App\Utils\MailChimpHelper;
  58. use App\Utils\HootsuiteHelper;
  59. use Vich\UploaderBundle\Storage\StorageInterface;
  60. use Vich\UploaderBundle\Mapping\PropertyMapping;
  61. use \Swift_Mailer as Swift_Mailer;
  62. use \Swift_Message as Swift_Message;
  63. use Symfony\Component\DependencyInjection\ContainerInterface as Container;
  64. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  65. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  66. use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient;
  67. use Google\Analytics\Data\V1beta\DateRange;
  68. use Google\Analytics\Data\V1beta\Dimension;
  69. use Google\Analytics\Data\V1beta\Metric;
  70. use Google\Analytics\Data\V1beta\RunReportRequest;
  71. use Twig\Environment;
  72. //TODO: Clean up uses in all controllers
  73. class ContentController extends DefaultController
  74. {
  75.     /**
  76.     * @Route("/uptime")
  77.     */
  78.     public function uptime(
  79.         Request $request
  80.     ) {
  81.         $stmt $this->getDoctrine()->getManager()->getConnection()->query("SELECT 1 + 1 as res");
  82.         $res $stmt->fetch();
  83.         return new JsonResponse($res["res"], 200, [], true);
  84.     }
  85.     /**
  86.     * @Route("/content-queue-test")
  87.     */
  88.     public function contentQueueTest(
  89.         Request $request,
  90.         ContentHelper $contentHelper
  91.     ) {
  92.         $session $request->getSession();
  93.         $content_ids $session->get("queued_content_ids", []);
  94.         return new JsonResponse(implode(", "$content_ids), 200, [], true);
  95.     }
  96.     /**
  97.     * @Route("/content-queue-clear")
  98.     */
  99.     public function contentQueueClear(
  100.         Request $request,
  101.         ContentHelper $contentHelper
  102.     ) {
  103.         $session $request->getSession();
  104.         $session->remove("queued_content_ids");
  105.         return new JsonResponse("OK"200, [], true);
  106.     }
  107.     
  108.     
  109.     //TODO: RCS only?
  110.     public function contentMembersOnlyCheck($content) {
  111.         if($content->getMembersOnly() && (!$this->user || (!$this->user->isMember() && !$this->user->isAdmin()))) {
  112.             $this->addFlash("warning""This page is only accessible to RCS Club members. Continue below to become a member and access this page.");
  113.             return $this->redirectToRoute("rcs-club-sign-up");
  114.         }
  115.     }
  116.     
  117.     //TODO: Why are these needed for admin edit routes?
  118.     //      & move this to a different controller
  119.     /**
  120.      * @Route("/ckeditor_upload", name="ckeditor_upload")
  121.      */
  122.     public function ckeditor_upload (
  123.         Request $request
  124.     ) {
  125.         
  126.     }
  127.     
  128.     /**
  129.      * @Route("/ckeditor_browse", name="ckeditor_browse")
  130.      */
  131.     public function ckeditor_browse (
  132.         Request $request
  133.     ) {
  134.         return $this->defaultRender("easy_admin/file-browse.html.twig", [
  135.         
  136.         ]);
  137.     }
  138.     // displays the meet the rcs influencers page
  139.     // requires a content object to be passed as $content
  140.     public function meetinfluencers(
  141.         Request $request,
  142.         ContentHelper $helper,
  143.         CustomerHelper $customerHelper,
  144.         $content ""
  145.     ) {
  146.         $cat_id 479;
  147.         if($this->site_code == 3) {//SiteConfig::SITE_MCS
  148.             $cat_id 1346;
  149.         }
  150.         if($this->site_code == 4) { //SiteConfig::SITE_CCS
  151.             $cat_id 1445;
  152.         }
  153.         $customers $customerHelper->getCustomersByCategory($cat_id$this->site_code);
  154.         return $this->defaultRender("content/tmpl/meet-rcs-influencers.html.twig", [
  155.             "content" => $content,
  156.             "customers" => $customers,
  157.         ]);
  158.     }
  159.     // displays the podcasts list page
  160.     public function podcasts(
  161.         Request $request,
  162.         ContentHelper $helper,
  163.         MediaHelper $mediaHelper,
  164.         $content ""
  165.     ) {
  166.         $podcasts $helper->getContent(Content::PODCAST$content->getSlug(), "published""desc"00true"*"true)["content"];
  167.         $images = [];
  168.         foreach($podcasts as $c) {
  169.             $cm $c->getContentMetaByKey("podcast_image");
  170.             if(is_null($cm) || $cm->getMetavalue() == 0) {
  171.                 $images[] = "";
  172.             }
  173.             else {
  174.                 $m $mediaHelper->getMediaByOldId($cm->getMetavalue());
  175.                 $images[] = $m;
  176.             }
  177.         }
  178.         return $this->defaultRender("content/tmpl/podcasts.html.twig", [
  179.             "content" => $content,
  180.             "podcasts" => $podcasts,
  181.             "images" => $images,
  182.             "meta" => ["adGroup" => "rlw"],
  183.         ]);
  184.     }
  185.     
  186.     /**
  187.      * @Route("/post/{slug}", name="post_master")
  188.      */
  189.     public function post(
  190.         Request $request,
  191.         ContentHelper $contentHelper,
  192.         $slug ""
  193.     ) {
  194.         /*if($this->site_code == Content::SITE_CCS && (!$this->user || (!$this->user->isMember() && !$this->user->isAdmin()))) {
  195.             return $this->redirectToRoute("sign-in_ccs");
  196.         }*/
  197.         $post $contentHelper->getPostBySlug($slug);
  198.         
  199.         $recommendPost $contentHelper->getRecommendedPosts($post->getCategory() ? $post->getCategory() : (!empty($post->getSecondaryCategories()) ? $post->getSecondaryCategories()[0] : null), 3$post->getId());
  200.         return $this->contentMembersOnlyCheck($post) ??
  201.         $this->defaultRender("content/content.html.twig", [
  202.             "content" => $post,
  203.             "meta" => [
  204.                 "title" => $post->getTitle(),
  205.                 "recommended" => $recommendPost,
  206.             ],
  207.         ]);
  208.     }
  209.     
  210.     /**
  211.      * @Route("/gallery/{slug}",name="gallery_master")
  212.      */
  213.     public function gallery (
  214.         Request $request,
  215.         ContentHelper $helper,
  216.         $slug
  217.     ) {
  218.         $gallery $helper->getContentBySlug(Content::GALLERY$slug);
  219.         
  220.         //TODO: Should we have site specific code here? or override in RCS controller?
  221.         $breadcrumbs = [];
  222.         if($this->site_code == Content::SITE_RCS) {
  223.             $bread_title "Roofing Galleries";
  224.             $bread_href "/roofing-galleries";
  225.             $category $gallery->getCategory();
  226.             if($category && $category->getSlug() == "partner-galleries") {
  227.                 $bread_title "Partner Galleries";
  228.                 $bread_href "/partner-galleries";
  229.             }
  230.             $breadcrumbs[] = [
  231.                 "title" => $bread_title,
  232.                 "href" => $bread_href,
  233.             ];
  234.         }
  235.         
  236.         $breadcrumbs[] = [
  237.             "title" => $gallery->getTitle(),
  238.             "href" => "/partner-galleries/{$gallery->getSlug()}",
  239.         ];
  240.         return $this->defaultRender("content/content.html.twig", [
  241.             "content" => $gallery,
  242.             "pagenum" => 1,
  243.             "meta" => [
  244.                 "title" => $gallery->getTitle(),
  245.                 "breadcrumbs" => $breadcrumbs
  246.             ]
  247.         ]);
  248.     }
  249.     
  250.     /**
  251.      * @Route("/podcast/{slug}", name="podcast_master")
  252.      */
  253.     public function podcast (
  254.         Request $request,
  255.         ContentHelper $helper,
  256.         $slug ""
  257.     ) {
  258.         $podcast $helper->getContentBySlug(Content::PODCAST$slug);
  259.         
  260.         $primaryCategory $podcast->getCategory();
  261.         $categories $podcast->getSecondaryCategories();
  262.         
  263.         $breadcrumbs = [];
  264.         
  265.         $parent_breadcrumb "";
  266.         if($primaryCategory && $primaryCategory->getSlug() == "partner-podcast") {
  267.             $breadcrumbs[] = [
  268.                 "title" => "Partner Podcasts",
  269.                 "href" => "/partner-podcast",
  270.             ];
  271.         }
  272.         else {
  273.             $breadcrumbs[] = [
  274.                 "title" => "Podcasts",
  275.                 "href" => "/podcasts",
  276.             ];
  277.         }
  278.         
  279.         foreach($categories as $category) {
  280.             if($category->getTaxonomy() == "rcs-podcast-type") {
  281.                 $parent_breadcrumb = [
  282.                     "title" => $category->getTitle(),
  283.                     "href" => "/podcasts/{$category->getSlug()}",
  284.                 ];
  285.             }
  286.         }
  287.         
  288.         if($parent_breadcrumb) {
  289.             $breadcrumbs[] = $parent_breadcrumb;
  290.         }
  291.         $breadcrumbs[] = [
  292.             "title" => $podcast->getTitle(),
  293.             "href" => "/podcast/{$podcast->getSlug()}",
  294.         ];
  295.         
  296.         return $this->defaultRender("content/content.html.twig", [
  297.             "content" => $podcast,
  298.             "pagenum" => 1//< is this needed?
  299.             "meta" => array (
  300.                 "title" => $podcast->getTitle(),
  301.                 "breadcrumbs" => $breadcrumbs
  302.             )
  303.         ]);
  304.     }
  305.     
  306.     /**
  307.      * @Route("/webinar/{slug}", name="webinar_master")
  308.      */
  309.     public function webinar (
  310.         Request $request,
  311.         ContentHelper $helper,
  312.         $slug ""
  313.     ) {
  314.         $webinar $helper->getContentBySlug(Content::WEBINAR$slug);
  315.         
  316.         return $this->contentMembersOnlyCheck($webinar) ??
  317.         $this->defaultRender("content/content.html.twig", [
  318.             "content" => $webinar,
  319.             "pagenum" => 1,
  320.             "meta" => [
  321.                 "title" => $webinar->getTitle(),
  322.         "adgroup" => "rlw"
  323.             ],
  324.         ]);
  325.     }
  326.     
  327.     /**
  328.      * @Route("/promos-rebates/{slug}", name="promos_master")
  329.      */
  330.     public function promos (
  331.         Request $request,
  332.         ContentHelper $contentHelper,
  333.         $slug
  334.     ) {
  335.         $promo $contentHelper->getContentBySlug(Content::PROMOS_REBATES$slug);
  336.         return $this->defaultRender("content/content.html.twig", [
  337.             "content" => $promo,
  338.             "pagenum" => "",
  339.             "meta" => [
  340.                 "title" => $promo->getTitle(),
  341.                 "breadcrumbs" => [
  342.                     [
  343.                         "title" => "Promos &amp; Rebates"//TODO: rework breadcrumbs?
  344.                         "href" => "/promos-rebates",
  345.                     ],
  346.                     [
  347.                         "title" => $promo->getTitle(),
  348.                         "href" => "/promo/{$promo->getSlug()}",
  349.                     ],
  350.                 ]
  351.             ]
  352.         ]);
  353.     }
  354.     
  355.     /**
  356.      * @Route("/ebooks/{slug}", name="ebook_master")
  357.      */
  358.     public function ebook (
  359.         Request $request,
  360.         ContentHelper $contentHelper,
  361.         $slug
  362.     ) {
  363.         $ebook $contentHelper->getContentBySlug(Content::EBOOK$slug);
  364.         $ebooksHref "/ebooks";
  365.         if($this->site_code == SiteConfig::SITE_AAR) {
  366.             $ebooksHref "/ebooks-aar";
  367.         }
  368.         elseif($this->site_code == SiteConfig::SITE_MCS) {
  369.             $ebooksHref "/ebooks-mcs";
  370.         }
  371.         elseif($this->site_code == SiteConfig::SITE_CCS) {
  372.             $ebooksHref "/ebooks";
  373.         }
  374.         return $this->defaultRender("content/content.html.twig", [
  375.             "content" => $ebook,
  376.             "pagenum" => 1,
  377.             "meta" => [
  378.                 "title" => $ebook->getTitle(),
  379.                 "breadcrumbs" => [
  380.                     [
  381.                         "title" => "eBooks",
  382.                         "href" => $ebooksHref,
  383.                     ],
  384.                     [
  385.                         "title" => $ebook->getTitle(),
  386.                         "href" => "/ebook/{$ebook->getSlug()}",
  387.                     ],
  388.                 ],
  389.             ]
  390.         ]);
  391.     }
  392.     public function ebooks(
  393.         Request $request,
  394.         ContentHelper $contentHelper,
  395.         CategoryHelper $categoryHelper,
  396.         CustomerHelper $customerHelper,
  397.         $slug,
  398.         $content "",
  399.         $customer ""
  400.     ) {
  401.         
  402.         if($slug == "partner-ebooks") {
  403.             $eBooks $contentHelper->getEbooks($customer);
  404.             $customers $customerHelper->customerHasEbooks();
  405.             return $this->defaultRender("content/tmpl/ebooks.html.twig",[
  406.                 "slug" => $slug,
  407.                 "content" => $content,
  408.                 "customers" => $customers,
  409.                 "eBooks" => $eBooks,
  410.                 "meta" => [
  411.                     "title" => "Partner eBooks",
  412.                     "breadcrumbs" => [
  413.                         [
  414.                             "title" => "Partner eBooks",
  415.                             "href" => "/partner-ebooks",
  416.                         ]
  417.                     ],
  418.                 ]
  419.             ]);
  420.         }
  421.         else {
  422.             $eBooks $contentHelper->getEbooks();
  423.             if($this->site_code == SiteConfig::SITE_AAR) {
  424.                 $categories $categoryHelper->getPopulatedCategoriesByTaxonomy('aar_ebook-category'$this->site_code);
  425.             }
  426.             else {
  427.                 $categories $categoryHelper->getPopulatedCategoriesByTaxonomy('ebook-category'$this->site_code);
  428.             }
  429.             foreach($categories as $key => $category) {
  430.                 if($category->getSlug() == "ebooks-misfits") {
  431.                     unset($categories[$key]);
  432.                 }
  433.             }
  434.             $ebooksHref "/ebooks";
  435.             if($this->site_code == SiteConfig::SITE_AAR) {
  436.                 $ebooksHref "/ebooks-aar";
  437.             }
  438.             elseif($this->site_code == SiteConfig::SITE_MCS) {
  439.                 $ebooksHref "/ebooks-mcs";
  440.             }
  441.             elseif($this->site_code == SiteConfig::SITE_CCS) {
  442.                 $ebooksHref "/ebooks-ccs";
  443.             }
  444.             
  445.             return $this->defaultRender("content/tmpl/ebooks.html.twig",[
  446.                 "slug" => $slug,
  447.                 "content" => $content,
  448.                 "categories" => $categories,
  449.                 "eBooks" => $eBooks,
  450.                 "meta" => [
  451.                     "title" => "eBooks",
  452.                     "breadcrumbs" => [
  453.                         [
  454.                             "title" => "eBooks",
  455.                             "href" => $ebooksHref,
  456.                         ]
  457.                     ],
  458.                 ]
  459.             ]);
  460.         }
  461.     }
  462.     
  463.     /**
  464.      * @Route("/contests-and-games/{slug}",
  465.      *      requirements={"slug"="^[a-zA-Z0-9\-]+$"},
  466.      *      name="contests_master"
  467.      * )
  468.      */
  469.     public function contests (
  470.         Request $request,
  471.         ContentHelper $contentHelper,
  472.         $slug
  473.     ) {
  474.         $contest $contentHelper->getContentBySlug(Content::CONTEST_GAMES$slug);
  475.         return $this->defaultRender("content/content.html.twig", [
  476.             "content" => $contest,
  477.             "pagenum" => 1,
  478.             "meta" => [
  479.                 "title" => $contest->getTitle(),
  480.                 "breadcrumbs" => [
  481.                     [
  482.                         "title" => "Contests &amp; Games",
  483.                         "href" => "/contests-and-games",
  484.                     ],
  485.                     [
  486.                         "title" => $contest->getTitle(),
  487.                         "href" => "/contests-and-games/{$contest->getSlug()}",
  488.                     ]
  489.                 ]
  490.             ]
  491.         ]);
  492.     }
  493.     
  494.     /**
  495.      * @Route("/award/{slug}", name="award_master")
  496.      */
  497.     public function award (
  498.         Request $request,
  499.         ContentHelper $contentHelper,
  500.         $slug
  501.     ) {
  502.         $award $contentHelper->getContentBySlug(Content::AWARD$slug);
  503.         return $this->defaultRender("content/content.html.twig", [
  504.             "content" => $award,
  505.             "pagenum" => "",
  506.             "meta" => array (
  507.                 "title" => $award->getTitle(),
  508.                 "breadcrumbs" => array (
  509.                     array (
  510.                         "title" => "Awards",
  511.                         "href" => "/awards",
  512.                     ),
  513.                     array (
  514.                         "title" => $award->getTitle(),
  515.                         "href" => "/award/{$award->getSlug()}",
  516.                     ),
  517.                 )
  518.             )
  519.         ]);
  520.     }
  521.     
  522.     /**
  523.      * @Route("/scholarship/{slug}", name="scholarship_master")
  524.      */
  525.     public function scholarship (
  526.         Request $request,
  527.         ContentHelper $contentHelper,
  528.         $slug
  529.     ) {
  530.         $scholarship $contentHelper->getContentBySlug(Content::SCHOLARSHIP$slug);
  531.         return $this->defaultRender("content/content.html.twig", [
  532.             "content" => $scholarship,
  533.             "pagenum" => "",
  534.             "meta" => array (
  535.                 "title" => $scholarship->getTitle(),
  536.                 "breadcrumbs" => array (
  537.                     array (
  538.                         "title" => "Scholarships",
  539.                         "href" => "/scholarships",
  540.                     ),
  541.                     array (
  542.                         "title" => $scholarship->getTitle(),
  543.                         "href" => "/scholarship/{$scholarship->getSlug()}",
  544.                     ),
  545.                 )
  546.             )
  547.         ]);
  548.     }
  549.     /**
  550.      * @Route("/video/{slug}", name="video_master")
  551.      */
  552.     public function video (
  553.         Request $request,
  554.         ContentHelper $contentHelper,
  555.         $slug
  556.     ) {
  557.         $video $contentHelper->getContentBySlug(Content::VIDEO$slug);
  558.         return $this->defaultRender("content/content.html.twig", [
  559.             "content" => $video,
  560.             "pagenum" => "",
  561.             "meta" => array (
  562.                 "title" => $video->getTitle(),
  563.                 "breadcrumbs" => array (
  564.                     array (
  565.                         "title" => "Videos",
  566.                         "href" => "/videos",
  567.                     ),
  568.                     array (
  569.                         "title" => $video->getTitle(),
  570.                         "href" => "/video/{$video->getSlug()}",
  571.                     ),
  572.                 )
  573.             )
  574.         ]);
  575.     }
  576.     /**
  577.      * @Route("/r-club-perk/{slug}", name="r-club-perk_master")
  578.      */
  579.     public function rClubPerk (
  580.         Request $request,
  581.         ContentHelper $contentHelper,
  582.         $slug
  583.     ) {
  584.         $perk $contentHelper->getContentBySlug(Content::R_CLUB_PERK$slug);
  585.         return $this->defaultRender("content/content.html.twig", [
  586.             "content" => $perk,
  587.             "pagenum" => "",
  588.             "meta" => array (
  589.                 "title" => $perk->getTitle(),
  590.                 "breadcrumbs" => array (
  591.                     array (
  592.                         "title" => "R-Club Perks",
  593.                         "href" => "/members-only",
  594.                     ),
  595.                     array (
  596.                         "title" => $perk->getTitle(),
  597.                         "href" => "/r-club-perk/{$perk->getSlug()}",
  598.                     ),
  599.                 )
  600.             )
  601.         ]);
  602.     }
  603.     
  604.     
  605.     /**
  606.      * Classified Listing Route
  607.      *
  608.      * @Route(
  609.      *      "/our-listings/{page}/{keywords}/{location}/{category}/{areas}",
  610.      *      defaults={ "page"="_", "keywords"="_", "location"="_", "category"="_", "areas"="_" },
  611.      *      name="classifiedIndex_master",
  612.      *      methods={"GET"}
  613.      * )
  614.      */
  615.     public function classifiedIndex (
  616.         Request $request,
  617.         ContentHelper $contentHelper,
  618.         CategoryHelper $categoryHelper,
  619.         $page "_",
  620.         $keywords "_",
  621.         $location "_",
  622.         $category "_",
  623.         $areas "_"
  624.     ) {
  625.         try {
  626.             $pagingSize 25;
  627.             $group $request->get("c");
  628.             if ($group) {
  629.                  $group $categoryHelper->getCategoryBySlug($group);
  630.             }
  631.             $records $contentHelper->getClassifiedListings($page$keywords$location$category$areas$group$pagingSize);
  632.             if(empty($records["listings"])) {
  633.                 //If no listings are found, try again on the first page. Prevents going past the final page due to pressing multiple buttons at once.
  634.                 $page 0;
  635.                 $records $contentHelper->getClassifiedListings($page$keywords$location$category$areas$group$pagingSize);
  636.             }
  637.             $listingCategories $categoryHelper->getCategoriesByTaxonomy("job_listing_category");
  638.             $listingAreas $categoryHelper->getCategoriesByTaxonomy("job_listing_type");
  639.             return $this->defaultRender("content/classified-index.html.twig", [
  640.                 "listings" => $records["listings"],
  641.                 "totalListings" => $records["total"],
  642.                 "listingCategories" => $listingCategories,
  643.                 "listingAreas" => $listingAreas,
  644.                 "group" => (($group) ? $group->getSlug() : ""),
  645.                 "page" => $page,
  646.                 "pagingSize" => $pagingSize,
  647.                 "keywords" => $keywords == "_" "" $keywords,
  648.                 "location" => $location == "_" "" $location,
  649.                 "category" => $category == "_" "" $category,
  650.                 "areas" => $areas == "_" "" explode("-"$areas),
  651.                 "meta" => [
  652.                     "title" => "Our Classified Listings",
  653.                     "breadcrumbs" => [
  654.                         [
  655.                             "title" => "Our Classified Listings",
  656.                             "href" => "/our-listings" . (($group) ? "?c={$group->getSlug()}""), // make sure to include any sorting categories
  657.                         ]
  658.                     ]
  659.                 ]
  660.             ]);
  661.         } catch (\Exception $e) {
  662.             throw $e;
  663.         }
  664.     }
  665.     
  666.     /**
  667.      * @Route("/listing/{slug}", name="classified_master")
  668.      */
  669.     public function classified(
  670.         Request $request,
  671.         ContentHelper $helper,
  672.         $slug ""
  673.     ) {
  674.         $listing $helper->getClassifiedBySlug($slug);
  675.         $meta_collection $listing->getContentmeta();
  676.         $content_meta = array();
  677.         foreach($meta_collection as $meta) {
  678.             $content_meta[$meta->getMetakey()] = $meta->getMetavalue();
  679.         }
  680.         $category_collection $listing->getSecondaryCategories();
  681.         $regions = array();
  682.         foreach($category_collection as $category) {
  683.             if($category->getTaxonomy() == "job_listing_type") {
  684.                 $regions[] = $category->getTitle();
  685.             }
  686.         }
  687.         if(count($regions) > 1) {
  688.             $region "Multiple";
  689.         }
  690.         elseif(count($regions) == 1) {
  691.             $region $regions[0];
  692.         }
  693.         else {
  694.             //Should never be empty
  695.             $region "No Region";
  696.         }
  697.         
  698.         return $this->defaultRender("content/content.html.twig", [
  699.             "content" => $listing,
  700.             "content_meta" => $content_meta,
  701.             "region" => $region,
  702.             "autoplay" => isset($_GET['autoplay']) && $_GET["autoplay"] == true false,
  703.             "meta" => [
  704.                 "title" => "Our Classified Listings",
  705.                 "breadcrumbs" => [
  706.                     [
  707.                         "title" => "Our Classified Listings",
  708.                         "href" => "/our-listings",
  709.                     ],
  710.                     [
  711.                         "title" => $listing->getTitle(),
  712.                         "href" => "/listing/{$listing->getSlug()}"
  713.                     ]
  714.                 ]
  715.             ]
  716.         ]);
  717.     }
  718.     
  719.     /**
  720.     * @Route(name="classified_request_info", methods={"POST"})
  721.     */
  722.     public function classifiedRequestInfo(
  723.         Request $request,
  724.         ContentHelper $contentHelper,
  725.         SessionInterface $session,
  726.         EmailHelper $emailHelper
  727.     ) {
  728.         $referer $request->headers->get('referer');
  729.         
  730.         if($emailHelper->checkCaptcha($request->get("g-recaptcha-response"))) {
  731.             $l $request->get("lead");
  732.             $lead = new Lead();
  733.             $lead->setFirstname($request->get('fname'));
  734.             $lead->setLastname($request->get('lname'));
  735.             $lead->setEmail($request->get('email'));
  736.             $lead->setIpAddress($request->getClientIp());
  737.             $lead->setRefUrl($request->headers->get("referer"));
  738.             $lead->setUserAgent($request->headers->get("User-Agent"));
  739.             $ref_url $request->headers->get("referer");
  740.             if($ref_url) {
  741.                 $slug strtok(substr($ref_urlstrrpos($ref_url'/') + 1), '?');
  742.                 if($slug) {
  743.                     $content $contentHelper->getContentBySlugRaw($slug);
  744.                     $lead->setContent($content);
  745.                 }
  746.             }
  747.             $em $this->getDoctrine()->getManager();
  748.             $em->persist($lead);
  749.             $em->flush();
  750.             $pooled null;
  751.             if($request->get("contact_email")) {
  752.                 $reply_text $request->get('fname') ? "Click here to respond to {$request->get('fname')}"Click here to reply";
  753.                 $pooled $emailHelper->sendEmail(trim($request->get("contact_email")), "New submission from Classified Listing Contact Form", [
  754.                     ["p" => "Hello {$request->get('contact_name')},"],
  755.                     ["p" => "{$request->get('fname')} {$request->get('lname')} ({$request->get('email')}) has replied to your \"{$request->get('listing_title')}\" classified listing with the following message:"],
  756.                     ["p" => "{$request->get('message')}"],
  757.                     ["button" => ["href" => "mailto:{$request->get('email')}""text" => $reply_text]],
  758.                 ], $request->files);
  759.             }
  760.             if ($pooled) {
  761.                 $emailHelper->sendEmail($request->get("email"), "Classified Listing Contact Confirmation", [
  762.                     ["p" => "Thanks for contacting us! We will get in touch with you shortly."],
  763.                 ]);
  764.                 $this->addFlash("success""Thanks for contacting us! We will get in touch with you shortly.");
  765.                 return new RedirectResponse($referer);
  766.                 /*
  767.                 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.
  768.                 print_r($session->get("last_route"));
  769.                 return $this->redirectToRoute($session->get("last_route")["name"], array_merge($session->get("last_route")["params"], ["message" => ["type" => "success", "text" => "Email sent"]]));
  770.                 */
  771.             }
  772.         }
  773.         else {
  774.             //temp2-5
  775.             //$this->addFlash("danger", "The reCAPTCHA was invalid. Please try again.");
  776.             return new RedirectResponse($referer);
  777.         }
  778.         $session->getFlashBag()->add('danger''There was an error sending your request. Please try again later.');
  779.         return new RedirectResponse($referer);
  780.     }
  781.     
  782.     //--Directory Start--
  783.     /**
  784.      * @Route(
  785.      *      "/our-directory/{page}/{category}/{type}/{search}/{location}/{state}",
  786.      *      defaults={"page"="", "category"="", "type"="", "search"="", "location"="", "state"=""},
  787.      *      name="directoryIndex_master",
  788.      *      methods={"GET"}
  789.      * )
  790.      */
  791.     public function directoryIndex (
  792.         Request $request,
  793.         ContentHelper $helper,
  794.         $page "",
  795.         $category "",
  796.         $type "",
  797.         $search "",
  798.         $location "",
  799.         $state ""
  800.     ) {
  801.         $page = (int) $page;
  802.         $records $helper->getDirectoryListings($page$category$type$search$location$state);
  803.         $categories $helper->getDirectoryCategories();
  804.         $stateOptions Customer::STATES_PROVINCES;
  805.         $search = ($search == "_") ? "" $search;
  806.         $breadcrumbs = [
  807.             [
  808.                 "title" => strtoupper(SiteConfig::CONFIGS[$this->site_code]["site_code"]) . " Directory",
  809.                 "href" => "/our-directory/",
  810.             ]
  811.         ];
  812.         return $this->defaultRender("content/directory.html.twig", [
  813.             "listings" => $records["listings"],
  814.             "total" => $records["total"],
  815.             "page" => $page,
  816.             "limit" => ContentHelper::DEFAULT_LIMIT,
  817.             "search" => $search,
  818.             "locations" => $location,
  819.             "states" => $state,
  820.             "stateOptions" => $stateOptions,
  821.             "categories" => $categories,
  822.             "category" => $category,
  823.             "filters" => $type,
  824.             "show_filters" => $request->query->get("filter") !== "0",
  825.             "meta" => [
  826.                 "title" => strtoupper(SiteConfig::CONFIGS[$this->site_code]["site_code"]) . " Directory",
  827.                 "breadcrumbs" => $breadcrumbs,
  828.             ]
  829.         ]);
  830.     }
  831.     
  832.     
  833.     /**
  834.      * @Route(
  835.      *      "/directory/{slug}",
  836.      *      name="directory_page_master",
  837.      *      methods={"GET"}
  838.      * )
  839.      */
  840.     public function directory(
  841.         Request $request,
  842.         ContentHelper $helper,
  843.         CategoryHelper $categoryHelper,
  844.         $slug ""
  845.     ) {
  846.         $directory $helper->getDirectoryBySlug($slug);
  847.         //$customer = $directory->getCustomers()->first();
  848.         $customer $directory->getDirectory();
  849.         $level $customer->getCustomerLevelString($this->site_code);
  850.         $types $customer->getCustomerTypeArray();
  851.         // hide or show areas of template
  852.         /*
  853.         $show_promotions = (
  854.             (in_array(Customer::TYPE_DISTRIBUTORS_STRING, $types) && ($level == "Partner" || $level == "Premium" || $level == "Best" || $level == "Better" || $level == "Good")) ||
  855.             (in_array(Customer::TYPE_PRODUCTS_SERVICES_STRING, $types) && ($level == "Partner" || $level == "Premium" || $level == "Best" || $level == "Better" || $level == "Good")) ||
  856.             (in_array(Customer::TYPE_ASSOCIATIONS_STRING, $types)) ||
  857.             (in_array(Customer::TYPE_RCS_PARTNERS_STRING, $types))
  858.         );
  859.         */
  860.         
  861.         $show_promotions $level && $level != "Standard";
  862.         // In case we want to break this up more
  863.         $show_photos $show_promotions;
  864.         $show_videos $show_promotions;
  865.         $show_education $show_promotions;
  866.         $show_ebooks $show_promotions;
  867.         $show_contestgames $show_promotions;
  868.         $show_awards $show_promotions;
  869.         $show_scholarships $show_promotions;
  870.         $show_upcoming $show_promotions;
  871.         $show_newsletters $show_promotions;
  872.         $show_coffeeblog $show_promotions;
  873.         $show_literature $show_promotions;
  874.         $show_podcasts $show_promotions;
  875.         $show_webinars $show_promotions;
  876.         $show_classifieds $show_promotions;
  877.         $show_buy_online $show_promotions;
  878.         $show_video $show_promotions;
  879.         $show_products $show_promotions;
  880.         
  881.         //Todo: use content helper function to pull these
  882.         //Spanish
  883.         try {
  884.           $spanishCat $categoryHelper->getCategoryBySlug("en-espanol")->getId();
  885.         }catch(\Exception $e) {
  886.           $spanishCat null;
  887.         }
  888.         $spanish_content = [];
  889.         
  890.         if($spanishCat) {
  891.           $sql implode(" ", [
  892.             "SELECT content",
  893.             "FROM",
  894.               "App\Entity\Content content",
  895.             "JOIN ",
  896.               "content.secondary_categories sc",
  897.             "LEFT JOIN ",
  898.               "content.customers c",
  899.             "WHERE",
  900.                 "sc.id = :id and content.status = 1 and c.id = :cid",
  901.             "ORDER BY content.created_at DESC",
  902.           ]);
  903.           
  904.           $entityManager $this->getDoctrine()->getManager();
  905.           $query $entityManager->createQuery($sql)
  906.             ->setParameter(":id"$spanishCat)
  907.             ->setParameter":cid"$customer->getId())
  908.             ->setFirstResult(0)
  909.             ->setMaxResults(4);
  910.             
  911.           $spanish_content $query->getResult();
  912.         }
  913.         //International
  914.         try {
  915.             $intCat $categoryHelper->getCategoryBySlug("international")->getId();
  916.           }catch(\Exception $e) {
  917.             $intCat null;
  918.           }
  919.           $int_content = [];
  920.           
  921.           if($intCat) {
  922.             $sql implode(" ", [
  923.               "SELECT content",
  924.               "FROM",
  925.                 "App\Entity\Content content",
  926.               "JOIN ",
  927.                 "content.secondary_categories sc",
  928.               "LEFT JOIN ",
  929.                 "content.customers c",
  930.               "WHERE",
  931.                   "sc.id = :id and content.status = 1 and c.id = :cid",
  932.               "ORDER BY content.created_at DESC",
  933.             ]);
  934.             
  935.             $entityManager $this->getDoctrine()->getManager();
  936.             $query $entityManager->createQuery($sql)
  937.               ->setParameter(":id"$intCat)
  938.               ->setParameter":cid"$customer->getId())
  939.               ->setFirstResult(0)
  940.               ->setMaxResults(4);
  941.               
  942.             $int_content $query->getResult();
  943.           }
  944.           //Canada
  945.           try {
  946.             $canadaCat $categoryHelper->getCategoryBySlug("canada")->getId();
  947.           }catch(\Exception $e) {
  948.             $canadaCat null;
  949.           }
  950.           $canada_content = [];
  951.           
  952.           if($canadaCat) {
  953.             $sql implode(" ", [
  954.               "SELECT content",
  955.               "FROM",
  956.                 "App\Entity\Content content",
  957.               "JOIN ",
  958.                 "content.secondary_categories sc",
  959.               "LEFT JOIN ",
  960.                 "content.customers c",
  961.               "WHERE",
  962.                   "sc.id = :id and content.status = 1 and c.id = :cid",
  963.               "ORDER BY content.created_at DESC",
  964.             ]);
  965.             
  966.             $entityManager $this->getDoctrine()->getManager();
  967.             $query $entityManager->createQuery($sql)
  968.               ->setParameter(":id"$canadaCat)
  969.               ->setParameter":cid"$customer->getId())
  970.               ->setFirstResult(0)
  971.               ->setMaxResults(4);
  972.               
  973.             $canada_content $query->getResult();
  974.           }
  975.         
  976.         
  977.         
  978.         // Whether to hide the footer ad - should this be used?
  979.         //$hide_ad = $row["level"] != "Standard";
  980.         
  981.         
  982.         $breadcrumbs = [
  983.             [
  984.                 "title" => strtoupper(SiteConfig::CONFIGS[$this->site_code]["site_code"]) . " Directory",
  985.                 "href" => "/our-directory/",
  986.             ],
  987.             [
  988.                 "title" => $directory->getTitle(),
  989.                 "href" => "/directory/{$directory->getSlug()}",
  990.             ]
  991.         ];
  992.         return $this->defaultRender("content/content.html.twig", [
  993.             "content" => $directory,
  994.             "customer" => $customer,
  995.             "show_promotions" => $show_promotions,
  996.             "show_photos" => $show_photos,
  997.             "show_videos" => $show_videos,
  998.             "show_education" => $show_education,
  999.             "show_ebooks" => $show_ebooks,
  1000.             "show_contestgames" => $show_contestgames,
  1001.             "show_awards" => $show_awards,
  1002.             "show_scholarships" => $show_scholarships,
  1003.             "show_upcoming" => $show_upcoming,
  1004.             "show_newsletters" => $show_newsletters,
  1005.             "show_coffeeblog" => $show_coffeeblog,
  1006.             "show_literature" => $show_literature,
  1007.             "show_podcasts" => $show_podcasts,
  1008.             "show_webinars" => $show_webinars,
  1009.             "show_classifieds" => $show_classifieds,
  1010.             "show_buy_online" => $show_buy_online,
  1011.             "show_products" => $show_products,
  1012.             "show_video" => $show_video,
  1013.             "buy_online_posts" => $helper->getPaginatedContentByType(Content::POST41""$customer"buy-online"false),
  1014.             "video_posts" => $helper->getPaginatedContentByType(Content::POST31""$customer"partner-videos"false),
  1015.             "latest_news" => $helper->getPaginatedContentByType(Content::POST31""$customer"newsroom"false),
  1016.             "upcoming_events" => $helper->getPaginatedContentByType(Content::EVENT31""$customer""false),
  1017.             "lunch_and_learn" => $helper->getPaginatedContentByType(Content::WEBINAR31""$customer"on-demand-lunch-learn"false),
  1018.             "webinars" => $helper->getPaginatedContentByType(Content::WEBINAR31""$customer""false"on-demand-lunch-learn"),
  1019.             "spanish_content" => $spanish_content,
  1020.             "int_content" => $int_content,
  1021.             "canada_content" => $canada_content,
  1022.             "email_is_valid" => filter_var($customer->getEmail(), FILTER_VALIDATE_EMAIL),
  1023.             "meta" => [
  1024.                 "title" => $directory->getTitle(),
  1025.                 "breadcrumbs" => $breadcrumbs,
  1026.                 "root" => "/directory/".$directory->getSlug(),
  1027.             ]
  1028.         ]);
  1029.     }
  1030.     
  1031.     /**
  1032.      * @Route("/directory/{slug}/posts/{page}", name="directory_posts_master")
  1033.      */
  1034.     public function directoryPosts(
  1035.         Request $request,
  1036.         ContentHelper $helper,
  1037.         $slug "",
  1038.         $page 1
  1039.     ) {
  1040.         $directory $helper->getDirectoryBySlug($slug);
  1041.         $customer $directory->getDirectory();
  1042.         
  1043.         $length 10;
  1044.         $posts $helper->getPaginatedContentByType(Content::POST$length$page""$customer"newsroom"false);
  1045.         $total $helper->countPostsByCustomer($customer);
  1046.         $breadcrumbs = [
  1047.             [
  1048.                 "title" => strtoupper(SiteConfig::CONFIGS[$this->site_code]["site_code"]) . " Directory",
  1049.                 "href" => "/our-directory/",
  1050.             ],
  1051.             [
  1052.                 "title" => $directory->getTitle(),
  1053.                 "href" => "/directory/{$directory->getSlug()}",
  1054.             ],
  1055.             [
  1056.                 "title" => "Posts",
  1057.                 "href" => "/directory/{$directory->getSlug()}/posts",
  1058.             ]
  1059.         ];
  1060.         return $this->defaultRender("content/post.html.twig", [
  1061.             "customer" => $customer,
  1062.             "posts" => $posts,
  1063.             "total" => $total,
  1064.             "length" => $length,
  1065.             "page" => $page,
  1066.             "meta" => [
  1067.                 "title" => $directory->getTitle(),
  1068.                 "breadcrumbs" => $breadcrumbs,
  1069.                 "root" => "/directory/".$directory->getSlug()."/posts",
  1070.             ]
  1071.         ]);
  1072.     }
  1073.     
  1074.     
  1075.     /**
  1076.        * @Route("/directory/{slug}/content/buy-online/{page}", name="directory_buyonline_content_master")
  1077.        */
  1078.     public function directoryBuyOnlineContent(
  1079.       Request $request,
  1080.       ContentHelper $helper,
  1081.       $slug "",
  1082.       $type "2",
  1083.       $page 1
  1084.     ) {
  1085.         $directory $helper->getDirectoryBySlug($slug); // get directory from url
  1086.         //$customer = $directory->getCustomers()->first(); // gets the directory customer
  1087.         $customer $directory->getDirectory();
  1088.         $length 10//10 per page
  1089.         
  1090.         $contents $helper->getContent(
  1091.           "*",
  1092.            "buy-online",
  1093.            "published",
  1094.            "desc",
  1095.            ($page 1),
  1096.            $length,
  1097.            true,
  1098.            "*",
  1099.            true//secondary categories
  1100.            false,
  1101.            false,
  1102.            false,
  1103.           $customer->getId()
  1104.           );
  1105.         $total $contents["total"];
  1106.         $posts $contents["content"];
  1107.         $breadcrumbs = [
  1108.           [
  1109.             "title" => strtoupper(SiteConfig::CONFIGS[$this->site_code]["site_code"]) . " Directory",
  1110.             "href" => "/our-directory/",
  1111.           ],
  1112.           [
  1113.             "title" => $directory->getTitle(),
  1114.             "href" => "/directory/{$directory->getSlug()}",
  1115.           ],
  1116.           [
  1117.             "title" => "Buy Online",
  1118.             "href" => "/directory/{$directory->getSlug()}/buy-online",
  1119.           ]
  1120.         ];
  1121.         return $this->defaultRender("content/post.html.twig", [
  1122.           "customer" => $customer,
  1123.           "posts" => $posts,
  1124.           "total" => $total,
  1125.           "length" => $length,
  1126.           "page" => $page,
  1127.           "meta" => [
  1128.             "title" => $directory->getTitle(),
  1129.                     "breadcrumbs" => $breadcrumbs,
  1130.                     "root" => "/directory/".$directory->getSlug()."/content/buy-online",
  1131.           ]
  1132.         ]);
  1133.     }
  1134.     //todo: make these types of routes generic
  1135.     /**
  1136.      * @Route("/directory/{slug}/content/spanish/{page}", name="directory_spanish_content_master")
  1137.      */
  1138.     public function directorySpanishContent(
  1139.     Request $request,
  1140.     ContentHelper $helper,
  1141.     $slug "",
  1142.     $type "2",
  1143.     $page 1
  1144.     ) {
  1145.         $directory $helper->getDirectoryBySlug($slug); // get directory from url
  1146.         //$customer = $directory->getCustomers()->first(); // gets the directory customer
  1147.         $customer $directory->getDirectory();
  1148.         $length 10//10 per page
  1149.         
  1150.         $contents $helper->getContent(
  1151.         "*",
  1152.             "en-espanol",
  1153.             "published",
  1154.             "desc",
  1155.             ($page 1),
  1156.             $length,
  1157.             true,
  1158.             "*",
  1159.             true//secondary categories
  1160.             false,
  1161.             false,
  1162.             false,
  1163.         $customer->getId()
  1164.         );
  1165.         $total $contents["total"];
  1166.         $posts $contents["content"];
  1167.         $breadcrumbs = [
  1168.         [
  1169.             "title" => strtoupper(SiteConfig::CONFIGS[$this->site_code]["site_code"]) . " Directory",
  1170.             "href" => "/our-directory/",
  1171.         ],
  1172.         [
  1173.             "title" => $directory->getTitle(),
  1174.             "href" => "/directory/{$directory->getSlug()}",
  1175.         ],
  1176.         [
  1177.             "title" => "Spanish Content",
  1178.             "href" => "/directory/{$directory->getSlug()}/spanish",
  1179.         ]
  1180.         ];
  1181.         return $this->defaultRender("content/post.html.twig", [
  1182.         "customer" => $customer,
  1183.         "posts" => $posts,
  1184.         "total" => $total,
  1185.         "length" => $length,
  1186.         "page" => $page,
  1187.         "meta" => [
  1188.             "title" => $directory->getTitle(),
  1189.                     "breadcrumbs" => $breadcrumbs,
  1190.                     "root" => "/directory/".$directory->getSlug()."/content/spanish",
  1191.         ]
  1192.         ]);
  1193.     }
  1194.     
  1195.     /**
  1196.      * @Route("/directory/{slug}/content/international/{page}", name="directory_international_content_master")
  1197.      */
  1198.     public function directoryInternationalContent(
  1199.         Request $request,
  1200.         ContentHelper $helper,
  1201.         $slug "",
  1202.         $type "2",
  1203.         $page 1
  1204.         ) {
  1205.             $directory $helper->getDirectoryBySlug($slug); // get directory from url
  1206.             //$customer = $directory->getCustomers()->first(); // gets the directory customer
  1207.             $customer $directory->getDirectory();
  1208.     
  1209.             $length 10//10 per page
  1210.             
  1211.             $contents $helper->getContent(
  1212.             "*",
  1213.                 "international",
  1214.                 "published",
  1215.                 "desc",
  1216.                 ($page 1),
  1217.                 $length,
  1218.                 true,
  1219.                 "*",
  1220.                 true//secondary categories
  1221.                 false,
  1222.                 false,
  1223.                 false,
  1224.             $customer->getId()
  1225.             );
  1226.             $total $contents["total"];
  1227.             $posts $contents["content"];
  1228.     
  1229.             $breadcrumbs = [
  1230.             [
  1231.                 "title" => strtoupper(SiteConfig::CONFIGS[$this->site_code]["site_code"]) . " Directory",
  1232.                 "href" => "/our-directory/",
  1233.             ],
  1234.             [
  1235.                 "title" => $directory->getTitle(),
  1236.                 "href" => "/directory/{$directory->getSlug()}",
  1237.             ],
  1238.             [
  1239.                 "title" => "International Content",
  1240.                 "href" => "/directory/{$directory->getSlug()}/international",
  1241.             ]
  1242.             ];
  1243.             return $this->defaultRender("content/post.html.twig", [
  1244.             "customer" => $customer,
  1245.             "posts" => $posts,
  1246.             "total" => $total,
  1247.             "length" => $length,
  1248.             "page" => $page,
  1249.             "meta" => [
  1250.                 "title" => $directory->getTitle(),
  1251.                         "breadcrumbs" => $breadcrumbs,
  1252.                         "root" => "/directory/".$directory->getSlug()."/content/international",
  1253.             ]
  1254.             ]);
  1255.         }
  1256.         
  1257.     /**
  1258.      * @Route("/directory/{slug}/content/canada/{page}", name="directory_canada_content_master")
  1259.      */
  1260.     public function directoryCanadaContent(
  1261.         Request $request,
  1262.         ContentHelper $helper,
  1263.         $slug "",
  1264.         $type "2",
  1265.         $page 1
  1266.         ) {
  1267.             $directory $helper->getDirectoryBySlug($slug); // get directory from url
  1268.             //$customer = $directory->getCustomers()->first(); // gets the directory customer
  1269.             $customer $directory->getDirectory();
  1270.     
  1271.             $length 10//10 per page
  1272.             
  1273.             $contents $helper->getContent(
  1274.             "*",
  1275.                 "canada",
  1276.                 "published",
  1277.                 "desc",
  1278.                 ($page 1),
  1279.                 $length,
  1280.                 true,
  1281.                 "*",
  1282.                 true//secondary categories
  1283.                 false,
  1284.                 false,
  1285.                 false,
  1286.             $customer->getId()
  1287.             );
  1288.             $total $contents["total"];
  1289.             $posts $contents["content"];
  1290.     
  1291.             $breadcrumbs = [
  1292.             [
  1293.                 "title" => strtoupper(SiteConfig::CONFIGS[$this->site_code]["site_code"]) . " Directory",
  1294.                 "href" => "/our-directory/",
  1295.             ],
  1296.             [
  1297.                 "title" => $directory->getTitle(),
  1298.                 "href" => "/directory/{$directory->getSlug()}",
  1299.             ],
  1300.             [
  1301.                 "title" => "Canada Content",
  1302.                 "href" => "/directory/{$directory->getSlug()}/canada",
  1303.             ]
  1304.             ];
  1305.             return $this->defaultRender("content/post.html.twig", [
  1306.             "customer" => $customer,
  1307.             "posts" => $posts,
  1308.             "total" => $total,
  1309.             "length" => $length,
  1310.             "page" => $page,
  1311.             "meta" => [
  1312.                 "title" => $directory->getTitle(),
  1313.                         "breadcrumbs" => $breadcrumbs,
  1314.                         "root" => "/directory/".$directory->getSlug()."/content/canada",
  1315.             ]
  1316.             ]);
  1317.         }
  1318.     
  1319.     /**
  1320.      * @Route("/directory/{slug}/content/lunch-and-learn/{page}", name="directory_lunch_and_learn_content_master")
  1321.      */
  1322.     public function directoryLunchAndLearnContent(
  1323.         Request $request,
  1324.         ContentHelper $helper,
  1325.         $slug "",
  1326.         $type "8",
  1327.         $page 1
  1328.         ) {
  1329.             $directory $helper->getDirectoryBySlug($slug); // get directory from url
  1330.             //$customer = $directory->getCustomers()->first(); // gets the directory customer
  1331.             $customer $directory->getDirectory();
  1332.     
  1333.             $length 10//10 per page
  1334.             
  1335.             $contents $helper->getContent(
  1336.             "*",
  1337.                 "on-demand-lunch-learn",
  1338.                 "published",
  1339.                 "desc",
  1340.                 ($page 1),
  1341.                 $length,
  1342.                 true,
  1343.                 "*",
  1344.                 true//secondary categories
  1345.                 false,
  1346.                 false,
  1347.                 false,
  1348.             $customer->getId()
  1349.             );
  1350.             $total $contents["total"];
  1351.             $posts $contents["content"];
  1352.     
  1353.             $breadcrumbs = [
  1354.             [
  1355.                 "title" => strtoupper(SiteConfig::CONFIGS[$this->site_code]["site_code"]) . " Directory",
  1356.                 "href" => "/our-directory/",
  1357.             ],
  1358.             [
  1359.                 "title" => $directory->getTitle(),
  1360.                 "href" => "/directory/{$directory->getSlug()}",
  1361.             ],
  1362.             [
  1363.                 "title" => "Lunch and Learn Content",
  1364.                 "href" => "/directory/{$directory->getSlug()}/lunch-and-learn",
  1365.             ]
  1366.             ];
  1367.             return $this->defaultRender("content/post.html.twig", [
  1368.             "customer" => $customer,
  1369.             "posts" => $posts,
  1370.             "total" => $total,
  1371.             "length" => $length,
  1372.             "page" => $page,
  1373.             "meta" => [
  1374.                 "title" => $directory->getTitle(),
  1375.                         "breadcrumbs" => $breadcrumbs,
  1376.                         "root" => "/directory/".$directory->getSlug()."/content/lunch-and-learn",
  1377.             ]
  1378.             ]);
  1379.         }
  1380.     /**
  1381.      * @Route("/directory/{slug}/content/{type}/{page}", name="directory_content_master")
  1382.      */
  1383.     public function directoryContent(
  1384.         Request $request,
  1385.         ContentHelper $helper,
  1386.         $slug "",
  1387.         $type 2,
  1388.         $page 1
  1389.     ) {
  1390.         $directory $helper->getDirectoryBySlug($slug);
  1391.         //$customer = $directory->getCustomers()->first();
  1392.         $customer $directory->getDirectory();
  1393.         $length 10;
  1394.         $posts $helper->getPaginatedContentByType($type$length$page""$customer);
  1395.         $total $helper->countContentByCustomer($type$customer);
  1396.         $breadcrumbs = [
  1397.             [
  1398.                 "title" => strtoupper(SiteConfig::CONFIGS[$this->site_code]["site_code"]) . " Directory",
  1399.                 "href" => "/our-directory/",
  1400.             ],
  1401.             [
  1402.                 "title" => $directory->getTitle(),
  1403.                 "href" => "/directory/{$directory->getSlug()}",
  1404.             ],
  1405.             [
  1406.                 "title" => Content::getTypeTextStatic($type),
  1407.                 "href" => "/directory/{$directory->getSlug()}/content/".$type,
  1408.             ]
  1409.         ];
  1410.         return $this->defaultRender("content/post.html.twig", [
  1411.             "customer" => $customer,
  1412.             "posts" => $posts,
  1413.             "total" => $total,
  1414.             "length" => $length,
  1415.             "page" => $page,
  1416.             "meta" => [
  1417.                 "title" => $directory->getTitle(),
  1418.                 "breadcrumbs" => $breadcrumbs,
  1419.                 "root" => "/directory/".$directory->getSlug()."/content/".$type,
  1420.             ]
  1421.         ]);
  1422.     }
  1423.     
  1424.     /**
  1425.      * @Route(
  1426.      *      "/directory/{slug}",
  1427.      *      name="directory_lead_master",
  1428.      *      methods={"POST"}
  1429.      * )
  1430.      */
  1431.     public function directoryPostLead (
  1432.         Request $request,
  1433.         ContentHelper $helper,
  1434.         Swift_Mailer $mailer,
  1435.         EmailHelper $emailHelper,
  1436.         ContentHelper $contentHelper,
  1437.         $slug ""
  1438.     ) {
  1439.         
  1440.         if($emailHelper->checkCaptcha($request->get("g-recaptcha-response"))) {
  1441.             
  1442.             $firstname $request->get("firstname");
  1443.             $lastname $request->get("lastname");
  1444.             $email $request->get("email");
  1445.             $message $request->get("comments");
  1446.             
  1447.             
  1448.             if( $contentHelper->isSpam($message) ||  $contentHelper->isSpam($email) ) {
  1449.                 //temporarily hiding this
  1450.                 //$this->addFlash("danger", "Invalid characters used.");
  1451.                 return new RedirectResponse($request->headers->get('referer'));
  1452.             }
  1453.             
  1454.             // update lead items
  1455.             $lead = new Lead();
  1456.             $lead->setFirstname($firstname);
  1457.             $lead->setLastname($lastname);
  1458.             $lead->setEmail($email);
  1459.             $lead->setComments($message);
  1460.             
  1461.             $lead->setIpAddress($request->getClientIp());
  1462.             $lead->setRefUrl($request->headers->get("referer"));
  1463.             $lead->setUserAgent($request->headers->get("User-Agent"));
  1464.             $content $contentHelper->getContentBySlugRaw($slug);
  1465.             $lead->setContent($content);
  1466.             
  1467.             $em $this->getDoctrine()->getManager();
  1468.             $em->persist($lead);
  1469.             $em->flush();
  1470.             
  1471.             
  1472.             // send e-mail
  1473.             
  1474.             $directory $helper->getDirectoryBySlug($slug);
  1475.             $customers $directory->getCustomers();
  1476.             
  1477.             //$recipients = array ("forms@intradatech.com");
  1478.             foreach ($customers as $customer) {
  1479.                 $recipients[] = $customer->getEmail();
  1480.             }
  1481.             //$recipients = implode(",", $recipients);
  1482.             
  1483.             $emailHelper->sendEmail(
  1484.                 $recipients,
  1485.                 "Contact Form Received",
  1486.                 [
  1487.                     ["p" => "Contact Form Received"],
  1488.                     ["table" => [
  1489.                         "First Name" => $firstname,
  1490.                         "Last Name" => $lastname,
  1491.                         "Email Address" => $email,
  1492.                         "Message" => $message,
  1493.                     ]],
  1494.                 ]
  1495.             );
  1496.             $this->addFlash("success""Thanks for contacting us! We will get in touch with you shortly.");
  1497.             return new RedirectResponse($request->headers->get('referer'));
  1498.         }
  1499.         $this->addFlash("danger""The reCAPTCHA was invalid. Please try again.");
  1500.         return new RedirectResponse($request->headers->get('referer'));
  1501.         // set invalid flag for javascript to show form again...
  1502.     }
  1503.     
  1504.     /**
  1505.      * @Route("/ebooks-by/{slug}", name="customerEbooks_master")
  1506.     */
  1507.     public function customerEBooks(
  1508.         Request $request,
  1509.         ContentHelper $contentHelper,
  1510.         $slug
  1511.     ){
  1512.         $directory $contentHelper->getDirectoryBySlug($slug);
  1513.         $customer $directory->getDirectory();
  1514.         // $customer = $directory->getDirectory();
  1515.         $eBooks $contentHelper->getEbooks($customer->getId());
  1516.         return $this->defaultRender("content/tmpl/ebooks-list.html.twig",[
  1517.             "eBooks" => $eBooks,
  1518.             "customer" => $customer,
  1519.             "meta" => [
  1520.                 "title" => $customer->getTitle(),
  1521.                 "breadcrumbs" => [
  1522.                     [
  1523.                         "title" => "Partner eBooks",
  1524.                         "href" => "/partner-ebooks",
  1525.                     ],
  1526.                     [
  1527.                         "title" => $customer->getTitle(),
  1528.                         "href" => "/ebooks-by/{$customer->getDirectoryContent()->getSlug()}",
  1529.                     ],
  1530.                 ],
  1531.             ]
  1532.         ]);
  1533.     }
  1534.     //--Directory End--
  1535.     
  1536.     
  1537.     //--Events Start--
  1538.     /**
  1539.      * @Route("/events/month/{month}/{year}", name="events_month_master")
  1540.      */
  1541.     public function events_month(
  1542.         Request $request,
  1543.         ContentHelper $helper,
  1544.         $slug "",
  1545.         $month 0,
  1546.         $year 0
  1547.     ) {
  1548.         if(!$month){$month date("n");}
  1549.         if(!$year){$year date("Y");}
  1550.         $date date("Y-m-d"strtotime("$year-$month-01"));
  1551.         $p_month date("Y-m-d"strtotime("-1 month"strtotime($date)));
  1552.         $n_month date("Y-m-d"strtotime("+1 month"strtotime($date)));
  1553.         return $this->defaultRender("content/tmpl/event-month.html.twig", [
  1554.             "meta" => [
  1555.                 "title" => "Events",
  1556.             ],
  1557.             "events_by_day" => $helper->getEventsByMonth($month$year),
  1558.             "month" => $month,
  1559.             "year" => $year,
  1560.             "date" => $date,
  1561.             "previous_month" => $p_month,
  1562.             "next_month" => $n_month,
  1563.         ]);
  1564.     }
  1565.     /**
  1566.      * @Route("/events/day/{month}/{day}/{year}/{search}", name="events_day_master")
  1567.      */
  1568.     public function events_day(
  1569.         Request $request,
  1570.         ContentHelper $helper,
  1571.         $slug "",
  1572.         $day 0,
  1573.         $month 0,
  1574.         $year 0,
  1575.         $search ""
  1576.     ) {
  1577.         if(!$day){$day date("j");}
  1578.         if(!$month){$month date("n");}
  1579.         if(!$year){$year date("Y");}
  1580.         $date date("Y-m-d"strtotime("$year-$month-$day"));
  1581.         $p_day date("Y-m-d"strtotime("-1 day"strtotime($date)));
  1582.         $n_day date("Y-m-d"strtotime("+1 day"strtotime($date)));
  1583.         $events $helper->getEventsByDay($date$search);
  1584.         $events_meta = array();
  1585.         foreach($events as $event) {
  1586.             $meta_collection $event->getContentmeta();
  1587.             $content_meta = array();
  1588.             foreach($meta_collection as $meta) {
  1589.                 $content_meta[$meta->getMetakey()] = $meta->getMetavalue();
  1590.             }
  1591.             $events_meta[$event->getId()] = $content_meta;
  1592.         }
  1593.         return $this->defaultRender("content/tmpl/event-day.html.twig", [
  1594.             "meta" => [
  1595.                 "title" => "Events",
  1596.             ],
  1597.             "events" => $events,
  1598.             "date" => $date,
  1599.             "previous_day" => $p_day,
  1600.             "next_day" => $n_day,
  1601.             "events_meta" => $events_meta,
  1602.             "search" => $search,
  1603.         ]);
  1604.     }
  1605.     /**
  1606.      * @Route("/events/{page}/{search}", name="events_master")
  1607.      */
  1608.     public function events(
  1609.         Request $request,
  1610.         ContentHelper $helper,
  1611.         $slug "",
  1612.         $page 1,
  1613.         $search ""
  1614.     ) {
  1615.         $limit ContentHelper::DEFAULT_LIMIT;
  1616.         if($request->request->has("eventSearch")) {
  1617.             $search $request->request->get("eventSearch");
  1618.         }
  1619.         if($request->request->has("eventDate")) {
  1620.             $date $request->request->get("eventDate");
  1621.             if(strtotime($date)) {
  1622.                 $date date("m/d/Y"strtotime($date));
  1623.                 return $this->redirectToRoute("events_day_master", [
  1624.                     "day" => date("d"strtotime($date)),
  1625.                     "month" => date("m"strtotime($date)),
  1626.                     "year" => date("Y"strtotime($date)),
  1627.                     "search" => $search
  1628.                 ]);
  1629.             }
  1630.             else {
  1631.                 $date "";
  1632.             }
  1633.         }
  1634.         if($search) {
  1635.             $events $helper->getPaginatedContentByType(Content::EVENT$limit$page$search);
  1636.         }
  1637.         else {
  1638.             $events $helper->getPaginatedContentByType(Content::EVENT$limit$page);
  1639.         }
  1640.         if($page == 0) {$page 1;}
  1641.         if($page == 1) {
  1642.             $p_page = -1;
  1643.         }
  1644.         else {
  1645.             $p_page $page 1;
  1646.         }
  1647.         if($page == -1) {
  1648.             $n_page 1;
  1649.         }
  1650.         else {
  1651.             $n_page $page 1;
  1652.         }
  1653.         if($page && abs($p_page) > ceil($helper->countPreviousEvents($search) / $limit)) {
  1654.             $p_page 0;
  1655.         }
  1656.         if($page && $n_page ceil($helper->countUpcomingEvents($search) / $limit)) {
  1657.             $n_page 0;
  1658.         }
  1659.         $events_meta = array();
  1660.         foreach($events as $event) {
  1661.             $meta_collection $event->getContentmeta();
  1662.             $content_meta = array();
  1663.             foreach($meta_collection as $meta) {
  1664.                 $content_meta[$meta->getMetakey()] = $meta->getMetavalue();
  1665.             }
  1666.             $events_meta[$event->getId()] = $content_meta;
  1667.         }
  1668.         return $this->defaultRender("content/tmpl/event-list.html.twig", [
  1669.             "meta" => [
  1670.                 "title" => "Events",
  1671.             ],
  1672.             "events" => $events,
  1673.             "pagenum" => $page,
  1674.             "previous_pagenum" => $p_page,
  1675.             "next_pagenum" => $n_page,
  1676.             "events_meta" => $events_meta,
  1677.             "search" => $search,
  1678.         ]);
  1679.     }
  1680.     /**
  1681.      * @Route("/event/{slug}", name="event_master")
  1682.      */
  1683.     public function event(
  1684.         Request $request,
  1685.         ContentHelper $helper,
  1686.         $slug ""
  1687.     ) {
  1688.         $event $helper->getEventBySlug($slug);
  1689.         $meta_collection $event->getContentmeta();
  1690.         $content_meta = array();
  1691.         foreach($meta_collection as $meta) {
  1692.             $content_meta[$meta->getMetakey()] = $meta->getMetavalue();
  1693.         }
  1694.         return $this->defaultRender("content/tmpl/event-single.html.twig", [
  1695.             "meta" => [
  1696.                 "title" => $event->getTitle(),
  1697.             ],
  1698.             "content" => $event,
  1699.             "content_meta" => $content_meta,
  1700.             "previous_event" => $helper->getPreviousEvent($event),
  1701.             "next_event" => $helper->getNextEvent($event),
  1702.         ]);
  1703.     }
  1704.     /**
  1705.      * @Route("/download-ics", name="download_ics_file")
  1706.     **/
  1707.     public function downloadICSFileAction(
  1708.         Request $request,
  1709.         ContentHelper $helper
  1710.     ){
  1711.         //if ($request->request->has("date_start")) {
  1712.             $ics_file $helper->make_ics_file($request->request->get("location"), $request->request->get("description"), $request->request->get("dtstart"),
  1713.             $request->request->get("dtend"), $request->request->get("summary"), $request->request->get("url"));
  1714.         //}
  1715.         $filename 'rooferscoffeshop-event.ics';
  1716.         $response  = new Response($ics_file);
  1717.          $disposition $response->headers->makeDisposition(
  1718.             ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  1719.             $filename
  1720.         );
  1721.         $response->headers->set('Content-Disposition'$disposition);
  1722.         return $response;
  1723.     }
  1724.     //--Events End
  1725.     
  1726.     
  1727.     //--Forums Start--
  1728.     
  1729.     /**
  1730.      * @Route("/forum", name="forums_master")
  1731.      */
  1732.     public function forums(
  1733.         Request $request,
  1734.         ContentHelper $contentHelper,
  1735.         $slug ""
  1736.     ) {
  1737.         $forums = array();
  1738.         foreach($contentHelper->getContentByType(Content::FORUM) as $forum) {
  1739.             $counts $contentHelper->countTopicsPostsByForum($forum->getSlug());
  1740.             $topics $contentHelper->getTopicsByForum($forum11);
  1741.             $topic "";
  1742.             foreach($topics as $t) {
  1743.                 $topic $t;
  1744.             }
  1745.             $featured $forum->getFeatured();
  1746.             $forums[] = [
  1747.                 "forum" => $forum,
  1748.                 "num_topics" => $counts["num_topics"],
  1749.                 "num_posts" => $counts["num_posts"],
  1750.                 "recent_topic" => $topic,
  1751.                 "featured" => $featured,
  1752.             ];
  1753.         }
  1754.         $num_topics = array();
  1755.         foreach($forums as $key => $row) {
  1756.             $num_topics[$key] = $row["num_topics"] + ($row["featured"] * 100000);
  1757.         }
  1758.         array_multisort($num_topicsSORT_DESC$forums);
  1759.         
  1760.         return $this->defaultRender("content/forums-page.html.twig", [
  1761.             "meta" => [
  1762.                 "title" => "Forums Archive",
  1763.                 "breadcrumbs" => [
  1764.                     [
  1765.                         "title" => "Our Forums",
  1766.                         "href" => "/forum",
  1767.                     ]
  1768.                 ]
  1769.             ],
  1770.             "forums" => $forums,
  1771.         ]);
  1772.     }
  1773.     
  1774.     /**
  1775.      * @Route("/forum/topic/{slug}/edit", name="forum_topic_edit_master")
  1776.      */
  1777.      public function forumTopicEdit(
  1778.         Request $request,
  1779.         ContentHelper $helper,
  1780.         $slug ""
  1781.      ) {
  1782.         $topic $helper->getTopicBySlug($slug);
  1783.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  1784.             $user $this->getUser();
  1785.             if($user) {
  1786.                 //$unrestricted = $user->getUserMetaValueByKey("rich_editing");
  1787.                 if($this->user->isAdmin()) {
  1788.                     //fully edit topic
  1789.                     if ($request->request->has("content")) {
  1790.                         $topic->setTitle($request->request->get("title"));
  1791.                         $topic->setContentFull($request->request->get("content"));
  1792.                         $topic->setPrnt($helper->getContentById($request->request->get("forum")));
  1793.                         $topic->setStatus($request->request->get("status"));
  1794.                         $em $this->getDoctrine()->getManager();
  1795.                         $em->persist($topic);
  1796.                         $em->flush();
  1797.                         $this->addFlash("success""Topic has been updated.");
  1798.                         return $this->redirectToRoute("forum_topic_master", ["slug" => $topic->getSlug(), "page" => "1"]);
  1799.                     }
  1800.                     return $this->defaultRender("content/tmpl/forum-topic-edit.html.twig", [
  1801.                         "content" => $topic,
  1802.                         //"unrestricted" => isset($unrestricted) ? $unrestricted : "",
  1803.                         "unrestricted" => true,
  1804.                         "forums" => $helper->getContentByType(Content::FORUM),
  1805.                         "admin" => true,
  1806.                     ]);
  1807.                 }
  1808.                 elseif($topic->getAuthor() == $user) {
  1809.                     //just allow them to edit the content and title
  1810.                     if ($request->request->has("content")) {
  1811.                         $topic->setTitle($request->request->get("title"));
  1812.                         $topic->setContentFull($request->request->get("content"));
  1813.                         $em $this->getDoctrine()->getManager();
  1814.                         $em->persist($topic);
  1815.                         $em->flush();
  1816.                         $this->addFlash("success""Topic has been updated.");
  1817.                         return $this->redirectToRoute("forum_topic_master", ["slug" => $topic->getSlug(), "page" => "1"]);
  1818.                     }
  1819.                     return $this->defaultRender("content/tmpl/forum-topic-edit.html.twig", [
  1820.                         "content" => $topic,
  1821.                         //"unrestricted" => isset($unrestricted) ? $unrestricted : "",
  1822.                         "unrestricted" => true,
  1823.                         "admin" => false,
  1824.                     ]);
  1825.                 }
  1826.             }
  1827.         }
  1828.         return $this->redirectToRoute("forum_topic_master", ["slug" => $topic->getSlug(), "page" => "1"]);
  1829.      }
  1830.      
  1831.      /**
  1832.      * @Route("/forum/topic/{slug}/delete", name="forum_topic_delete_master")
  1833.      */
  1834.      public function forumTopicDelete(
  1835.         Request $request,
  1836.         ContentHelper $helper,
  1837.         $slug ""
  1838.      ) {
  1839.         $topic $helper->getTopicBySlug($slug);
  1840.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  1841.             $user $this->getUser();
  1842.             if($user) {
  1843.                 if($this->user->isAdmin()) {
  1844.                     $topic->setStatus(Content::STATUS_INACTIVE);
  1845.                     $em $this->getDoctrine()->getManager();
  1846.                     $em->persist($topic);
  1847.                     $em->flush();
  1848.                     foreach($topic->getChildren() as $child) {
  1849.                         $child->setStatus(Content::STATUS_INACTIVE);
  1850.                         $em->persist($child);
  1851.                         $em->flush();
  1852.                     }
  1853.                     $this->addFlash("success""Topic has been deleted.");
  1854.                     return $this->redirectToRoute("forum_master", ["slug" => $topic->getPrnt()->getSlug(), "page" => "1"]);
  1855.                 }
  1856.             }
  1857.         }
  1858.      }
  1859.      /**
  1860.      * @Route("/forum/topic/{slug}/unsubscribe/{userid}", name="forum_topic_unsubscribe_master")
  1861.      */
  1862.      public function forumTopicUnsubscribe(
  1863.         Request $request,
  1864.         ContentHelper $helper,
  1865.         UserHelper $userhelper,
  1866.         $slug "",
  1867.         $userid ""
  1868.      ) {
  1869.         $topic $helper->getTopicBySlug($slug);
  1870.         $user $userhelper->getUserById($userid);
  1871.         $entityManager $this->getDoctrine()->getManager();
  1872.         if($topic->getAuthor() == $user) {
  1873.             $topic->setContentmetum("_notify_of_replies""0");
  1874.             $entityManager->persist($topic);
  1875.             $entityManager->flush();
  1876.         }
  1877.         foreach($topic->getActiveChildren() as $reply) {
  1878.             if($reply->getAuthor() == $user) {
  1879.                 $reply->setContentmetum("_notify_of_replies""0");
  1880.                 $entityManager->persist($reply);
  1881.                 $entityManager->flush();
  1882.             }
  1883.         }
  1884.         $this->addFlash("success""You will no longer receive email notifications about the \"{$topic->getTitle()}\" forum topic.");
  1885.         return $this->redirectToRoute("forum_master", ["slug" => $topic->getPrnt()->getSlug(), "page" => "1"]);
  1886.      }
  1887.      /**
  1888.      * @Route("/forum/topic/{slug}/spam", name="forum_topic_spam_master")
  1889.      */
  1890.      public function forumTopicSpam(
  1891.         Request $request,
  1892.         ContentHelper $helper,
  1893.         $slug ""
  1894.      ) {
  1895.         $topic $helper->getTopicBySlug($slug);
  1896.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  1897.             $user $this->getUser();
  1898.             if($user) {
  1899.                 if($this->user->isAdmin()) {
  1900.                     $forumUser $topic->getAuthor();
  1901.                     if($forumUser) {
  1902.                         $forumUser->markAsSpam();
  1903.                         $em $this->getDoctrine()->getManager();
  1904.                         $em->persist($forumUser);
  1905.                         $em->flush();
  1906.                         /* //Should we do this?
  1907.                         foreach($topic->getChildren() as $child) {
  1908.                             $child->setStatus(Content::STATUS_INACTIVE);
  1909.                             $em->persist($child);
  1910.                             $em->flush();
  1911.                         }
  1912.                         */
  1913.                         $this->addFlash("success""User has been marked as spam.");
  1914.                     }
  1915.                     else {
  1916.                         $this->addFlash("warning""There was a problem marking this user as spam.");
  1917.                     }
  1918.                     return $this->redirectToRoute("forum_master", ["slug" => $topic->getPrnt()->getSlug(), "page" => "1"]);
  1919.                 }
  1920.             }
  1921.         }
  1922.      }
  1923.     /**
  1924.      * @Route("/forum/topic/{slug}/{page}", name="forum_topic_master")
  1925.      */
  1926.     public function forumTopic(
  1927.         Request $request,
  1928.         ContentHelper $helper,
  1929.         EmailHelper $emailHelper,
  1930.         $slug "",
  1931.         $page 1
  1932.     ) {
  1933.         $topic $helper->getTopicBySlug($slug);
  1934.         $limit ContentHelper::FORUM_LIMIT;
  1935.         $forum $topic->getPrnt();
  1936.         //Members only check
  1937.         /*if($forum && $forum->getMembersOnly() && (!$this->user || (!$this->user->isMember() && !$this->user->isAdmin()))) {
  1938.             $this->addFlash("warning", "This forum is only accessible to RCS Club members. Continue below to become a member and access this forum.");
  1939.             return $this->redirectToRoute("rcs-club-sign-up");
  1940.         }*/
  1941.         if($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  1942.             
  1943.             //if ($form->isSubmitted() && $form->isValid()) {
  1944.             if ($request->request->has("reply-content")) {
  1945.                 $content = new Content();
  1946.                 
  1947.                 $entityManager $this->getDoctrine()->getManager();
  1948.                 $site $entityManager //TODO: test, add to default controller?
  1949.                     ->getRepository(Site::class)
  1950.                     ->findOneBy([
  1951.                         "id" => $this->site_code
  1952.                     ]);
  1953.                 $content->addSite($site);
  1954.                 
  1955.                 $content->setType(Content::FORUM_REPLY);
  1956.                 $content->setPrnt($topic);
  1957.                 $content->setPermission(1);
  1958.                 $user $this->getUser();
  1959.                 if($user) {
  1960.                     $content->setAuthor($user);
  1961.                 }
  1962.                 
  1963.                 if($emailHelper->checkInvisibleCaptcha($request->get("g-recaptcha-response"))) {
  1964.                     $notify = new ContentMeta();
  1965.                     $notify->setMetakey("_notify_of_replies");
  1966.                     $request->request->has("notify") ? $notify->setMetavalue(1) : $notify->setMetavalue(0);
  1967.                     $content->addContentmetum($notify);
  1968.                     $content_full $request->request->get("reply-content");
  1969.                     if(!$this->user->isAdmin()) {
  1970.                         $content_full preg_replace('/<a[^>]+>([^<]+)<\/a>/i','\1',$content_full);
  1971.                     }
  1972.                     $content->setContentFull($content_full);
  1973.                     if($helper->isSpam($request->request->get("reply-content"))) {
  1974.                         $content->setStatus(Content::STATUS_IN_REVIEW);
  1975.                     }
  1976.                     else {
  1977.                         $content->setStatus(Content::STATUS_ACTIVE);
  1978.                     }
  1979.                     $entityManager $this->getDoctrine()->getManager();
  1980.                     $entityManager->persist($content);
  1981.                     $entityManager->flush();
  1982.                     $this->addFlash("success""Your reply has been added.");
  1983.                     
  1984.                     if($topic->getContentMetaValueByKey("_notify_of_replies")) {
  1985.                         //forum_email
  1986.                         $pooled $emailHelper->sendEmail($topic->getAuthor()->getEmail(), "New Reply to one of your Forum Topics", [
  1987.                             ["p" => "Hello {$topic->getAuthor()},"],
  1988.                             ["p" => "{$content->getAuthor()} has replied to your forum topic <a href=\"{$topic->getFullURL($this->site_code)}\">\"{$topic->getTitle()}\"</a> with the following reply:"],
  1989.                             ["p" => "{$content->getContentFull()}"],
  1990.                             //["a" => ["href" => "dev.askaroofer.com/forum/topic/{$topic->getSlug()}/unsubscribe/{$topic->getAuthor()->getId()}", "text" => "Click Here to stop receiving these notifications"]],
  1991.                             ["a" => ["href" => "{$topic->getFullURL($this->site_code)}/unsubscribe/{$topic->getAuthor()->getId()}""text" => "Click Here to stop receiving these notifications"]],
  1992.                         ], [], """lauren@rooferscoffeeshop.com");
  1993.                     }
  1994.                     $notify_users = array();
  1995.                     foreach($topic->getActiveChildren() as $reply) {
  1996.                         if($reply != $content) {
  1997.                             if($reply->getContentMetaValueByKey("_notify_of_replies") && !in_array($reply->getAuthor(), $notify_users)
  1998.                                 && $reply->getAuthor() != $topic->getAuthor() && $reply->getAuthor() != $content->getAuthor()) {
  1999.                                 $notify_users[] = $reply->getAuthor();
  2000.                             }
  2001.                         }
  2002.                     }
  2003.                     foreach($notify_users as $notify_user) {
  2004.                         //forum_email
  2005.                         $pooled $emailHelper->sendEmail($notify_user->getEmail(), "New Reply to one of your Forum Topics", [
  2006.                             ["p" => "Hello {$notify_user},"],
  2007.                             ["p" => "{$content->getAuthor()} has replied to the forum topic <a href=\"{$topic->getFullURL($this->site_code)}\">\"{$topic->getTitle()}\"</a> with the following reply:"],
  2008.                             ["p" => "{$content->getContentFull()}"],
  2009.                             //["a" => ["href" => "dev.askaroofer.com/forum/topic/{$topic->getSlug()}/unsubscribe/{$notify_user->getId()}", "text" => "Click Here to stop receiving these notifications"]],
  2010.                             ["a" => ["href" => "{$topic->getFullURL($this->site_code)}/unsubscribe/{$notify_user->getId()}""text" => "Click Here to stop receiving these notifications"]],
  2011.                         ], [], """lauren@rooferscoffeeshop.com");
  2012.                     }
  2013.                     $session $request->getSession();
  2014.                     $route $session->get("this_route");
  2015.                     // return $this->redirectToRoute('task_success');
  2016.                     return $this->redirect($route["path"]);
  2017.                 }
  2018.                 else {
  2019.                     //failed the recaptcha check
  2020.                     $session $request->getSession();
  2021.                     $route $session->get("this_route");
  2022.                     return $this->redirect($route["path"]);
  2023.                 }
  2024.             }
  2025.         }
  2026.         $count $helper->countActiveChildren($topic);
  2027.         return $this->defaultRender("content/content.html.twig", [
  2028.             "meta" => [
  2029.                 "title" => $topic->getTitle(),
  2030.                 "breadcrumbs" => [
  2031.                     [
  2032.                         "title" => "Our Forums",
  2033.                         "href" => "/forum",
  2034.                     ],
  2035.                     [
  2036.                         "title" => $forum->getTitle(),
  2037.                         "href" => "/forum/{$forum->getSlug()}",
  2038.                     ],
  2039.                     [
  2040.                         "title" => $topic->getTitle(),
  2041.                         "href" => "/forum/topic/{$topic->getSlug()}",
  2042.                     ],
  2043.                 ],
  2044.             ],
  2045.             "content" => $topic,
  2046.             "replies" => $helper->getPaginatedChildren($topic$limit$pagetrue),
  2047.             "limit" => $limit,
  2048.             "pagenum" => $page,
  2049.             "totalcount" => $count,
  2050.             "totalpages" => ceil($count $limit),
  2051.             "baseurl" => $this->generateUrl('forum_topic_master', ['slug' => $slug]),
  2052.             //"form" => $form->createView(),
  2053.             //"unrestricted" => isset($unrestricted) ? $unrestricted : "",
  2054.             //let everyone be unrestricted (Vickie wants everyone to be able to post images for now)
  2055.             "unrestricted" => true,
  2056.         ]);
  2057.     }
  2058.     /**
  2059.      * @Route("/forum/reply/{id}/{action}", name="forum_reply_master")
  2060.      */
  2061.     public function forumReply(
  2062.         Request $request,
  2063.         ContentHelper $helper,
  2064.         $id "",
  2065.         $action ""
  2066.     ) {
  2067.         $reply $helper->getContentById($id);
  2068.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  2069.             $user $this->getUser();
  2070.             if($user) {
  2071.                 if($reply->getAuthor() == $user || $this->user->isAdmin()) {
  2072.                     //access granted
  2073.                     //$unrestricted = $user->getUserMetaValueByKey("rich_editing");
  2074.                     if($action == "edit") {
  2075.                         if ($request->request->has("reply-content")) {
  2076.                             $content_full $request->request->get("reply-content");
  2077.                             if(!$this->user->isAdmin()) {
  2078.                                 $content_full preg_replace('/<a[^>]+>([^<]+)<\/a>/i','\1',$content_full);
  2079.                             }
  2080.                             $reply->setContentFull($content_full);
  2081.                             $em $this->getDoctrine()->getManager();
  2082.                             $em->persist($reply);
  2083.                             $em->flush();
  2084.                             $this->addFlash("success""Reply has been updated.");
  2085.                             return $this->redirectToRoute("forum_topic_master", ["slug" => $reply->getPrnt()->getSlug(), "page" => "1"]);
  2086.                         }
  2087.                         return $this->defaultRender("content/tmpl/forum-reply-edit.html.twig", [
  2088.                             "content" => $reply,
  2089.                             //"unrestricted" => isset($unrestricted) ? $unrestricted : "",
  2090.                             "unrestricted" => true,
  2091.                         ]);
  2092.                     }
  2093.                     elseif ($action == "delete"){
  2094.                         $reply->setStatus(Content::STATUS_INACTIVE);
  2095.                         $em $this->getDoctrine()->getManager();
  2096.                         $em->persist($reply);
  2097.                         $em->flush();
  2098.                         $this->addFlash("success""Reply has been deleted.");
  2099.                         return $this->redirectToRoute("forum_topic_master", ["slug" => $reply->getPrnt()->getSlug(), "page" => "1"]);
  2100.                     }
  2101.                     elseif ($action == "spam"){
  2102.                         $user $reply->getAuthor();
  2103.                         if($user) {
  2104.                             $user->markAsSpam();
  2105.                             $em $this->getDoctrine()->getManager();
  2106.                             $em->persist($user);
  2107.                             $em->flush();
  2108.                             $this->addFlash("success""User has been marked as spam.");
  2109.                         }
  2110.                         else {
  2111.                             $this->addFlash("warning""There was a problem marking this user as spam.");
  2112.                         }
  2113.                         return $this->redirectToRoute("forum_topic_master", ["slug" => $reply->getPrnt()->getSlug(), "page" => "1"]);
  2114.                     }
  2115.                 }
  2116.             }
  2117.         }
  2118.         // no action was taken, return to the single reply view
  2119.          return $this->defaultRender("content/tmpl/forum-reply-single.html.twig", [ // or content/content
  2120.             "content" => $reply,
  2121.         ]);
  2122.     }
  2123.     /**
  2124.      * @Route(
  2125.      *        "/forum/search/{search}/{page}",
  2126.      *      defaults={"search"="", "page"=1},
  2127.      *        name="forum_search_master",
  2128.      *      methods={"GET"}
  2129.      * )
  2130.      */
  2131.     public function forumSearch(
  2132.         Request $request,
  2133.         ContentHelper $helper,
  2134.         $search "",
  2135.         $page 1
  2136.     ) {
  2137.         $limit ContentHelper::FORUM_LIMIT;
  2138.         return $this->defaultRender("content/forum-search.html.twig", [
  2139.             "meta" => [
  2140.                 "title" => "Forum Search Results",
  2141.             ],
  2142.             "results" => $helper->getForumSearchResults($search$limit$page),
  2143.             "search" => $search,
  2144.             "limit" => $limit,
  2145.             "pagenum" => $page,
  2146.             "totalcount" => $helper->countForumSearchResults($search),
  2147.             "totalpages" => ceil($helper->countForumSearchResults($search) / $limit),
  2148.             "baseurl" => $this->generateUrl('forum_search_master', ['search' => $search]),
  2149.         ]);
  2150.     }
  2151.     /**
  2152.      * @Route("/forum/{slug}/{page}", name="forum_master")
  2153.      */
  2154.     public function forum(
  2155.         Request $request,
  2156.         ContentHelper $helper,
  2157.         UserHelper $userhelper,
  2158.         EmailHelper $emailHelper,
  2159.         $slug "",
  2160.         $page 1
  2161.     ) {
  2162.         $forum $helper->getForumBySlug($slug);
  2163.         $limit ContentHelper::FORUM_LIMIT;
  2164.         //Members only check
  2165.         /*if($forum->getMembersOnly() && (!$this->user || (!$this->user->isMember() && !$this->user->isAdmin()))) {
  2166.             $this->addFlash("warning", "This forum is only accessible to RCS Club members. Continue below to become a member and access this forum.");
  2167.             return $this->redirectToRoute("rcs-club-sign-up");
  2168.         }*/
  2169.         //if ($form->isSubmitted() && $form->isValid()) {
  2170.         if ($request->request->has("content") && $request->request->has("title")) {
  2171.             if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  2172.                 $content = new Content();
  2173.                 
  2174.                 $entityManager $this->getDoctrine()->getManager();
  2175.                 $site $entityManager
  2176.                     ->getRepository(Site::class)
  2177.                     ->findOneBy([
  2178.                         "id" => $this->site_code
  2179.                     ]);
  2180.                 $content->addSite($site);
  2181.                 
  2182.                 $content->setType(Content::FORUM_TOPIC);
  2183.                 $content->setPrnt($forum);
  2184.                 $content->setPermission(1);
  2185.                 $user $this->getUser();
  2186.                 if($user) {
  2187.                     $content->setAuthor($user);
  2188.                     //$unrestricted = $user->getUserMetaValueByKey("rich_editing");
  2189.                 }
  2190.                 if($emailHelper->checkInvisibleCaptcha($request->get("g-recaptcha-response"))) {
  2191.                     $notify = new ContentMeta();
  2192.                     $notify->setMetakey("_notify_of_replies");
  2193.                     $request->request->has("notify") ? $notify->setMetavalue(1) : $notify->setMetavalue(0);
  2194.                     $content->addContentmetum($notify);
  2195.                     $content->setTitle($request->request->get("title"));
  2196.                     $content->setContentFull($request->request->get("content"));
  2197.                     $content->setSlug($helper->getUniqueSlug($content->getTitle(), ""$this->site_code));
  2198.                     if($helper->isSpam($request->request->get("title")) || $helper->isSpam($request->request->get("content"))) {
  2199.                         //Just preventing posting entirely for now instead of marking as in review since there is so much Korean spam.
  2200.                         //$content->setStatus(Content::STATUS_IN_REVIEW);
  2201.                         //$this->addFlash("warning", "Your new topic has triggered our automatic spam filter. If you believe this is an error, please contact a site administrator.");
  2202.                         $session $request->getSession();
  2203.                         $route $session->get("this_route");
  2204.                         return $this->redirect($route["path"]);
  2205.                     }
  2206.                     else {
  2207.                         //Not spam
  2208.                         $content->setStatus(Content::STATUS_ACTIVE);
  2209.                         $entityManager $this->getDoctrine()->getManager();
  2210.                         $entityManager->persist($content);
  2211.                         $entityManager->flush();
  2212.                         $this->addFlash("success""Your new topic \"{$content->getTitle()}\" has been added.");
  2213.                         //If it's a members only topic, notify members who are set to receive notifications
  2214.                         /*
  2215.                         if($forum->getMembersOnly()) {
  2216.                             $notify_users = $userhelper->getMembersToNotify("member_notification_forum");
  2217.                             if($notify_users) {
  2218.                                 foreach($notify_users as $notify_user) {
  2219.                                     //forum_email
  2220.                                     $pooled = $emailHelper->sendEmail($notify_user->getEmail(), "New Members Only Forum Topic", [
  2221.                                         ["p" => "Hello {$notify_user},"],
  2222.                                         ["p" => "{$content->getAuthor()} has posted a new topic to the R-Club forum: \"<a href='{$content->getFullURL()}'>{$content->getTitle()}</a>\"."],
  2223.                                         ["p" => "{$content->getContentFull()}"],
  2224.                                         ["a" => ["href" => "askaroofer.com/account", "text" => "Update your membership notification setting here to stop receiving these notifications"]],
  2225.                                     ]);
  2226.                                 }
  2227.                             }
  2228.                         }
  2229.                         */
  2230.                         //forum_email
  2231.                         $pooled $emailHelper->sendEmail(SiteConfig::CONFIGS[$this->site_code]["email_group"], "New Forum Topic", [
  2232.                             //["p" => "Hello {$notify_user},"],
  2233.                             ["p" => "{$content->getAuthor()} has posted a new topic to the forum: \"<a href='{$content->getFullURL($this->site_code)}'>{$content->getTitle()}</a>\"."],
  2234.                             ["p" => "{$content->getContentFull()}"],
  2235.                         ]);
  2236.                             
  2237.                     }
  2238.                 }
  2239.                 else {
  2240.                     //failed the recaptcha check
  2241.                     $session $request->getSession();
  2242.                     $route $session->get("this_route");
  2243.                     return $this->redirect($route["path"]);
  2244.                 }
  2245.             }
  2246.         }
  2247.         $count $helper->countActiveChildren($forum);
  2248.         return $this->defaultRender("content/content.html.twig", [
  2249.             "meta" => [
  2250.                 "title" => $forum->getTitle(),
  2251.                 "breadcrumbs" => [
  2252.                     [
  2253.                         "title" => "Our Forums",
  2254.                         "href" => "/forum",
  2255.                     ],
  2256.                     [
  2257.                         "title" => $forum->getTitle(),
  2258.                         "href" => "/forum/{$forum->getSlug()}",
  2259.                     ],
  2260.                 ],
  2261.             ],
  2262.             "content" => $forum,
  2263.             //"topics" => $helper->getPaginatedChildren($forum, $limit, $page),
  2264.             "topics" => $helper->getTopicsByForum($forum$limit$page),
  2265.             "limit" => $limit,
  2266.             "pagenum" => $page,
  2267.             "totalcount" => $count,
  2268.             "totalpages" => ceil($count $limit),
  2269.             "baseurl" => $this->generateUrl('forum_master', ['slug' => $slug]),
  2270.             //"form" => $form->createView(),
  2271.             //"unrestricted" => isset($unrestricted) ? $unrestricted : "", //if the user can post unrestricted HTML content
  2272.             "unrestricted" => true,
  2273.         ]);
  2274.     }
  2275.     
  2276.     /* End Forums */
  2277.     
  2278.     
  2279.     
  2280.     /**
  2281.      * @route("/rlw/{slug}",
  2282.      *     name="rlw-posts_master",
  2283.      *     defaults={"slug": ""}
  2284.      * )
  2285.      *
  2286.      */
  2287.     public function showRLWPage (
  2288.        Request $request,
  2289.        ContentHelper $contentHelper,
  2290.        $slug ""
  2291.     ) {
  2292.         
  2293.         try {
  2294.             if (!$slug || is_numeric($slug)) {
  2295.                 // show all rlw content...
  2296.                 
  2297.                 $page 1;
  2298.                 $limit 10;
  2299.                 
  2300.                 if (is_numeric($slug)) {
  2301.                     $page $slug;
  2302.                 }
  2303.                 
  2304.                 $data $contentHelper->getContent(
  2305.                    Content::THE_HUB,
  2306.                    "*",
  2307.                    "created",
  2308.                    "desc",
  2309.                    $page 1,
  2310.                    $limit
  2311.                 );
  2312.                 
  2313.                 $category = [
  2314.                     "title" => "Read Listen Watch - All Learning Resources<span id=\"spacer\"></span>",
  2315.                     "href" => "/rlw",
  2316.                 ];
  2317.                 
  2318.                 return $this->defaultRender("content/post.html.twig", array (
  2319.                    "posts" => $data["content"],
  2320.                    "total" => $data["total"],
  2321.                    "length" => $limit,
  2322.                    "page" => $page,
  2323.                    "category" => $category,
  2324.                    "meta" => array (
  2325.                        "root" => "/rlw",
  2326.                        "breadcrumbs" => [
  2327.                            [
  2328.                                "title" => "Learn Your Way",
  2329.                                "href" => "/read-listen-watch",
  2330.                            ],
  2331.                            [
  2332.                                "title" => "Read Listen Watch - All Learning Resources",
  2333.                                "href" => "/rlw",
  2334.                            ]
  2335.                        ]
  2336.                    )
  2337.                 ));
  2338.             }
  2339.             
  2340.             else {
  2341.                 $content $contentHelper->getContentBySlug(Content::THE_HUB$slug);
  2342.                 return $this->defaultRender("content/page.html.twig", [
  2343.                    "content" => $content,
  2344.                    
  2345.                    "meta" => [
  2346.                         "title" => $content->getTitle(),
  2347.                         "breadcrumbs" => [
  2348.                             [
  2349.                                 "title" => "Learn Your Way",
  2350.                                 "href" => "/read-listen-watch",
  2351.                             ],
  2352.                             [
  2353.                                 "title" => $content->getTitle(),
  2354.                                 "href" => $content->getURL(),
  2355.                             ]
  2356.                         ]
  2357.                     ],
  2358.                 ]);
  2359.             }
  2360.         }
  2361.         
  2362.         catch (Exception $e) {
  2363.             throw $e;
  2364.         }
  2365.     }
  2366.     /**
  2367.      * @Route("/thank-you/{slug}", name="thank-you-landing-page_master")
  2368.      *
  2369.      */
  2370.     public function showThankYouPage (
  2371.         ContentHelper $contentHelper,
  2372.         Request $request,
  2373.         $slug
  2374.     ) {
  2375.         //Thank you landing page
  2376.         try {
  2377.             $page $contentHelper->getThankYouPageBySlug($slug);
  2378.             return $this->defaultRender("content/thank-you-landing-page.html.twig", [
  2379.                 "page" => $page,
  2380.                 "meta" => [
  2381.                     "title" => $page->getTitle(),
  2382.                 ],
  2383.             ]);
  2384.         }
  2385.         catch (ResourceNotFoundException $e) {
  2386.         }
  2387.         return $this->defaultRender("errors/404.html.twig", [
  2388.         ]);
  2389.     }
  2390.     
  2391.     // requires a content object to be passed as $content
  2392.     public function comment(
  2393.         Request $request,
  2394.         ContentHelper $helper,
  2395.         EmailHelper $emailHelper,
  2396.         $content ""
  2397.     ) {
  2398.         $limit ContentHelper::DEFAULT_LIMIT;
  2399.         
  2400.         //Because this is used as an embedded controller, it receives a sub-request instead of the master request (that has the form submission data).
  2401.         //This line will set the request to the master request to allow it to be processed.
  2402.         $request $this->get('request_stack')->getMasterRequest();
  2403.         
  2404.         $comment = new Comment();
  2405.         $comment->setContent($content);
  2406.         
  2407.         //$form = $this->createForm(CommentType::class, $comment);
  2408.         
  2409.         //$form->handleRequest($request);
  2410.         
  2411.         if ($request->request->has("comment-text")) {
  2412.             
  2413.             //$comment = $form->getData();
  2414.             
  2415.             $comment->setApproved(0);
  2416.             $comment->setAuthorIP($_SERVER['REMOTE_ADDR']);
  2417.             $comment->setAgent($_SERVER['HTTP_USER_AGENT']);
  2418.             $comment->setCommentText($request->request->get("comment-text"));
  2419.             
  2420.             if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  2421.                 $user $this->getUser();
  2422.                 if($user->getRole() == 8) {
  2423.                     $comment->setApproved(1);
  2424.                 }
  2425.                 $comment->setUser($user);
  2426.                 $comment->setAuthor($user->getDisplayname());
  2427.                 $comment->setAuthorEmail($user->getEmail());
  2428.                 $comment->setApproved(1); //Change 3/25/21 to auto-approve per Heidi
  2429.             }
  2430.             else {
  2431.                 $comment->setAuthor($request->request->get("author"));
  2432.                 $comment->setAuthorEmail($request->request->get("email"));
  2433.                 $comment->setAuthorUrl($request->request->get("url"));
  2434.             }
  2435.             
  2436.             $entityManager $this->getDoctrine()->getManager();
  2437.             $entityManager->persist($comment);
  2438.             $entityManager->flush();
  2439.             
  2440.             $contentType strtolower($content->getTypeText());
  2441.             
  2442.             $emailHelper->sendEmail(
  2443.                 ["rcs@rooferscoffeeshop.com"],
  2444.                 "New Comment Added - {$content->getTitle()}",
  2445.                 [
  2446.                     ["p" => "A new comment has been added to the {$contentType} \"{$content->getTitle()}\"."],
  2447.                     ["p" => "User \"{$comment->getAuthor()}\" commented: \"{$comment->getCommentText()}\"."],
  2448.                     ["button" => [
  2449.                         "text" => "View Content",
  2450.                         "href" => "{$content->getFullURL($this->site_code)}",
  2451.                     ]],
  2452.                 ]
  2453.             );
  2454.             
  2455.             //redirect back (can't get to work yet bc of embedded controller)
  2456.             //$this->addFlash("success", "Your comment has been submitted and is awaiting approval.");
  2457.             /*
  2458.             $session = $request->getSession();
  2459.             $route = $session->get("this_route");
  2460.             $this->redirect($route["path"]);
  2461.             */
  2462.             
  2463.         }
  2464.         /*
  2465.         if ($form->isSubmitted() && $form->isValid()) {
  2466.             $comment = $form->getData();
  2467.             $comment->setApproved(0);
  2468.             $comment->setAuthorIP($_SERVER['REMOTE_ADDR']);
  2469.             $comment->setAgent($_SERVER['HTTP_USER_AGENT']);
  2470.             if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  2471.                 $user = $this->getUser();
  2472.                 if($user->getRole() == 8) {
  2473.                     $comment->setApproved(1);
  2474.                 }
  2475.                 $comment->setUser($user);
  2476.                 $comment->setAuthor($user->getDisplayname());
  2477.                 $comment->setAuthorEmail($user->getEmail());
  2478.             }
  2479.             $entityManager = $this->getDoctrine()->getManager();
  2480.             $entityManager->persist($comment);
  2481.             $entityManager->flush();
  2482.             //redirect back
  2483.             $this->addFlash("success", "Your comment has been submitted and is awaiting approval.");
  2484.         }
  2485.         */
  2486.         return $this->defaultRender("forms/comment.html.twig", [
  2487.             "comments" => $helper->getComments($content),
  2488.             //"form" => $form->createView(),
  2489.         ]);
  2490.     }
  2491.     
  2492.     /**
  2493.      * @Route("/search/{page}",
  2494.      *     name="search_master",
  2495.      *     defaults={"page": 1}
  2496.      * )
  2497.      */
  2498.     public function search (
  2499.        Request $request,
  2500.        ContentHelper $contentHelper,
  2501.        $page 1
  2502.     ) {
  2503.         $search $request->get("s");
  2504.         $data $contentHelper->search($search$page);
  2505.         
  2506.         return $this->defaultRender("content/search.html.twig", [
  2507.            "total" => $data["count"],
  2508.            "limit" => 15,
  2509.            "results" => $data["content"],
  2510.            "page" => $page,
  2511.            "search" => $search,
  2512.            "meta" => [
  2513.                "title" => "Search Results for {$search}",
  2514.            ]
  2515.         ]);
  2516.     }
  2517.     // requires a content object to be passed as $content
  2518.     public function partnerspage(
  2519.         Request $request,
  2520.         ContentHelper $contentHelper,
  2521.         $content ""
  2522.     ) {
  2523.         
  2524.         $directories $contentHelper->getDirectoryListings(0,"_","_","_","_","_",10000);
  2525.         
  2526.         return $this->defaultRender("content/tmpl/partners-page.html.twig", [
  2527.             "content" => $content,
  2528.             "directories" => $directories["listings"],
  2529.         ]);
  2530.     }
  2531.     
  2532.     // requires a content object to be passed as $content
  2533.     public function popoutAd(
  2534.         Request $request,
  2535.         ContentHelper $contentHelper,
  2536.         CustomerHelper $customerHelper,
  2537.         EmailHelper $emailHelper,
  2538.         MediaHelper $mediaHelper,
  2539.         $content ""
  2540.     ) {
  2541.         if($content instanceof Content) {
  2542.             $customer $content->getPrimaryCustomer();
  2543.             $popout $mediaHelper->getPopoutAdByCustomer($customer);
  2544.             if(!$popout) {
  2545.                 $popout $mediaHelper->getDefaultPopoutAd();
  2546.                 $customer $customerHelper->getCustomerById(110);
  2547.             }
  2548.         }
  2549.         else {
  2550.             //$content = ""; $customer = ""; $popout = "";
  2551.             $content "";
  2552.             $popout $mediaHelper->getDefaultPopoutAd();
  2553.             $customer $customerHelper->getCustomerById(110);
  2554.         }
  2555.         return $this->defaultRender("elements/popout-ad.html.twig", [
  2556.             "popout" => $popout,
  2557.             "customer" => $customer,
  2558.         ]);
  2559.     }
  2560.     
  2561.     // requires a content object to be passed as $content
  2562.     public function pinnedSidebarAd(
  2563.         Request $request,
  2564.         MediaHelper $mediaHelper,
  2565.         $base_url "",
  2566.         $uri "",
  2567.         $current_route ""
  2568.     ) {
  2569.         //$site_code = $this->site_code;
  2570.         $ad $mediaHelper->getPinnedAdByPosition($base_urlparse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH), $current_route"ad-sidebar");
  2571.         return $this->defaultRender("elements/sidebar-ad.html.twig", [
  2572.             "ad" => $ad
  2573.             //,"uri" => parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH)
  2574.         ]);
  2575.     }
  2576.     // requires a content object to be passed as $content
  2577.     public function pinnedCurtainAd(
  2578.         Request $request,
  2579.         MediaHelper $mediaHelper,
  2580.         $base_url "",
  2581.         $uri "",
  2582.         $current_route ""
  2583.     ) {
  2584.         $ad $mediaHelper->getPinnedAdByPosition($base_urlparse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH), $current_route"ad-curtain");
  2585.         return $this->defaultRender("elements/curtain-ad.html.twig", [
  2586.             "ad" => $ad
  2587.         ]);
  2588.     }
  2589.     
  2590.     
  2591.     /**
  2592.     * @Route("/quiz/{slug}", name="Quick Quiz")
  2593.     */
  2594.     public function getQuiz(
  2595.         Request $request,
  2596.         QuizHelper $quizHelper,
  2597.         $slug
  2598.     ){
  2599.         $cookies $request->cookies;
  2600.         if (!$this->user && !$cookies->has("$slug-quizToken")) {
  2601.             $nt uniqid();
  2602.             setcookie("$slug-quizToken"$nt,0,'','',true,true);
  2603.         }
  2604.         $quiz $quizHelper->getLandingPageBySlug($slug);
  2605.         //Static quiz templates:
  2606.         if ($quiz && in_array($slug, ["wdyfir""certainteed"]) && $this->site_code == Site::SITE_RCS) {
  2607.             return $this->defaultRender("content/quiz/$slug/landing.html.twig",$quiz);
  2608.         }
  2609.         else {
  2610.             //Dynamic Quizzes:
  2611.             $quiz $quizHelper->getQuizObjectBySlug($slug);
  2612.             if($quiz) {
  2613.                 return $this->defaultRender("content/quiz/dynamic/landing.html.twig", [
  2614.                     "quiz" => $quiz
  2615.                 ]);
  2616.             }
  2617.         }
  2618.     }
  2619.     /**
  2620.     * @Route("/quizExport/{quizId}", name="quiz_export")
  2621.     */
  2622.     public function quizExport(
  2623.         Request $request,
  2624.         QuizHelper $quizHelper,
  2625.         $quizId ""
  2626.     ) {
  2627.         $access false;
  2628.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  2629.             $user $this->getUser();
  2630.             if($user) {
  2631.                 if($this->user->isAdmin()) {
  2632.                     $access true;
  2633.                 }
  2634.             }
  2635.         }
  2636.         if(!$access) {
  2637.             return $this->defaultRender("errors/404.html.twig", []);
  2638.         }
  2639.         $quiz $quizHelper->getQuizById($quizId);
  2640.         $responses $quiz->getQuizResponses()->matching(Criteria::create()->orderBy(["datetaken" => Criteria::DESC]));
  2641.         $questions $quiz->getQuizQuestions()->matching(Criteria::create()->orderBy(["sort" => Criteria::ASC]));
  2642.         
  2643.         //Export / Spreadsheet
  2644.         $spreadsheet = new Spreadsheet();
  2645.         
  2646.         $spreadsheet = new Spreadsheet();
  2647.         $sheet $spreadsheet->getActiveSheet();
  2648.         
  2649.         //Sheet 1
  2650.         $rowNum 1;
  2651.         $sheet->setTitle("Quiz Results");
  2652.         $sheet->setCellValue("A{$rowNum}""Date Taken");
  2653.         $sheet->setCellValue("B{$rowNum}""Name");
  2654.         $sheet->setCellValue("C{$rowNum}""Email");
  2655.         $sheet->setCellValue("D{$rowNum}""Finished");
  2656.         $sheet->setCellValue("E{$rowNum}""Score");
  2657.         $colVal "F";
  2658.         foreach($questions as $question) {
  2659.             $sheet->setCellValue("{$colVal}{$rowNum}"$question->getTitle());
  2660.             $colVal++;
  2661.         }
  2662.         $sheet->getStyle("A1:{$colVal}1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFDDDDDD');
  2663.         $rowNum++;
  2664.         
  2665.         foreach($responses as $response) {
  2666.             if($questions->first() && !$response->getAnswerByQuestionId($questions->first()->getId())) {
  2667.                 continue; //Skip if first question isn't answered (caused by a bug)
  2668.             }
  2669.             $colVal "A";
  2670.             $name $response->getUser() ? $response->getUser()->getFullName() : $response->getNlFullName();
  2671.             $email $response->getUser() ? $response->getUser()->getEmail() : $response->getNlEmail();
  2672.             $sheet->setCellValue("{$colVal}{$rowNum}"$response->getDatetaken()->format("Y-m-d H:i:s")); $colVal++;
  2673.             $sheet->setCellValue("{$colVal}{$rowNum}"$name); $colVal++;
  2674.             $sheet->setCellValue("{$colVal}{$rowNum}"$email); $colVal++;
  2675.             $sheet->setCellValue("{$colVal}{$rowNum}"$response->getIsFinished() ? "Yes" "No"); $colVal++;
  2676.             //$sheet->setCellValue("{$colVal}{$rowNum}", $response->getMessage() ? $response->getMessage() : "N/A"); $colVal++;
  2677.             $sheet->setCellValue("{$colVal}{$rowNum}"$response->getScore()); $colVal++;
  2678.             foreach($questions as $question) {
  2679.                 $answer $response->getAnswerByQuestionId($question->getId());
  2680.                 $sheet->setCellValue("{$colVal}{$rowNum}"$answer $answer "");
  2681.                 $colVal++;
  2682.             }
  2683.             $rowNum++;
  2684.         }
  2685.         foreach(range("A",$sheet->getHighestColumn()) as $columnID) {
  2686.             $sheet->getColumnDimension($columnID)
  2687.                 ->setAutoSize(true);
  2688.         }
  2689.         
  2690.         //Finish and save
  2691.         //$spreadsheet->setActiveSheetIndexByName("Quiz Results");
  2692.         $writer = new Xlsx($spreadsheet);
  2693.         $filename "Quiz Export - {$quiz->getTitle()}.xlsx";
  2694.         $writer->save("../var/reports/quizzes/{$filename}");
  2695.         
  2696.         $response = new BinaryFileResponse("../var/reports/quizzes/{$filename}");
  2697.         $disposition $response->headers->makeDisposition(
  2698.             ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  2699.             $filename
  2700.         );
  2701.         $response->headers->set('Content-Disposition'$disposition);
  2702.         return $response;
  2703.     }
  2704.     /**
  2705.     * @Route("/quiz/{slug}/collect-information", name="Quiz-Lead",methods={"GET"})
  2706.     */
  2707.     public function quizLead(
  2708.         Request $request,
  2709.         QuizHelper $quizHelper,
  2710.         $slug
  2711.     ){
  2712.         $quiz $quizHelper->getQuizObjectBySlug($slug);
  2713.         $ref $request->query->get("ref");
  2714.         if (in_array($slug, ["wdyfir""certainteed"])) {
  2715.             return $this->defaultRender("content/quiz/$slug/infoCollector.html.twig", [
  2716.                 'ref'=>$ref,
  2717.                 'img'=>$quizHelper->getLandingPageBySlug($slug)['img']
  2718.             ]);
  2719.         }
  2720.         return $this->defaultRender("content/quiz/dynamic/infoCollector.html.twig", [
  2721.             'ref' => $ref,
  2722.             'quiz' => $quiz,
  2723.             //'img'=>$quizHelper->getLandingPageBySlug($slug)['img']
  2724.         ]);
  2725.         
  2726.     }
  2727.     /**
  2728.     * @Route("/quiz/{slug}/collect-information", name="Quiz-Lead-data", methods={"POST"})
  2729.     */
  2730.     public function quizLeadData(
  2731.         Request $request,
  2732.         QuizHelper $quizHelper,
  2733.         $slug
  2734.     ){
  2735.         $ref $request->request->get("ref");
  2736.         $fname $request->request->get("firstName");
  2737.         $lname $request->request->get("lastName");
  2738.         $email $request->request->get("email");
  2739.         $newsletter $request->request->get("newsletter");
  2740.         
  2741.         // normalize newsletter
  2742.         if($newsletter == "on") {
  2743.             $newsletter 1;
  2744.         }else{
  2745.             $newsletter 0;
  2746.         }
  2747.         // process information // save the lead
  2748.         $quizHelper->saveUnauthedQuizLead($fname$lname$email$ref$newsletter);
  2749.         
  2750.         $quizResponse $quizHelper->getQuizResponseByRefurl($ref);
  2751.         $quizHelper->sendQuizResultsEmail($quizResponse->getId());
  2752.         
  2753.         return $this->redirectToRoute("Quiz-Results", [
  2754.             "slug" => $slug,
  2755.             "ref" => $ref
  2756.         ]);
  2757.     }
  2758.     /**
  2759.     * @Route("/quiz/{slug}/{question}", name="Quick-Question", methods={"GET"})
  2760.     */
  2761.     public function getQuestionByQuizByNumber(
  2762.         Request $request,
  2763.         QuizHelper $quizHelper,
  2764.         $slug,
  2765.         $question
  2766.     ){
  2767.         $quiz $quizHelper->getQuizObjectBySlug($slug);
  2768.         if($quiz->getRequiresLogin() && !$this->user) {
  2769.             return $this->redirectToRoute("Quick Quiz", [
  2770.                 "slug" => $slug,
  2771.             ]);
  2772.         }
  2773.         
  2774.         $cookies $request->cookies;
  2775.         if ($this->user || $cookies->has("$slug-quizToken")) {
  2776.             $uid $this->user $this->user->getID() : $cookies->get("$slug-quizToken");
  2777.             $lastQuestionNumber $quizHelper->getInProgressQuizByID($slug,$uid);
  2778.             if ($lastQuestionNumber && $lastQuestionNumber+!= $question) {
  2779.                 return $this->redirectToRoute("Quick-Question", [
  2780.                     "slug" => $slug,
  2781.                     "question" => $lastQuestionNumber+1
  2782.                 ]);
  2783.             }elseif(!$lastQuestionNumber && $question!=1){
  2784.                 return $this->redirectToRoute("Quick-Question", [
  2785.                     "slug" => $slug,
  2786.                     "question" => 1
  2787.                 ]);
  2788.             }
  2789.         }
  2790.         if (in_array($slug, ["wdyfir""certainteed"])) {
  2791.             $q $quizHelper->getQuestionOptionsByQuizByNumber($slug$question);
  2792.             if ($q) {
  2793.                 return $this->defaultRender("content/quiz/$slug/question.html.twig",$q);
  2794.             }else{
  2795.                 return $this->defaultRender("errors/404.html.twig", []);
  2796.             }
  2797.         }
  2798.         else {
  2799.             //Dynamic Quizzes:
  2800.             $number $question;
  2801.             $quiz $quizHelper->getQuizObjectBySlug($slug);
  2802.             $question $quiz->getQuestionByNumber($number);
  2803.             if($question) {
  2804.                 return $this->defaultRender("content/quiz/dynamic/question.html.twig", [
  2805.                     "quiz" => $quiz,
  2806.                     "question" => $question,
  2807.                     "number" => $number
  2808.                 ]);
  2809.             }
  2810.         }
  2811.         
  2812.     }
  2813.     /**
  2814.     * @Route("/quiz/{slug}/{question}", name="Question-Answer", methods={"POST"})
  2815.     */
  2816.     public function saveQuestionResponse(
  2817.         Request $request,
  2818.         QuizHelper $quizHelper,
  2819.         MailChimpHelper $mailChimpHelper,
  2820.         $slug,
  2821.         $question
  2822.     ){
  2823.         $cookies $request->cookies;
  2824.         $qid $quizHelper->getQuizBySlug($slug)['id'];
  2825.         if (!$this->user) {
  2826.             $uid NULL;
  2827.             $nt $cookies->get("$slug-quizToken");
  2828.         }else{
  2829.             $uid $this->user->getID();
  2830.             $nt NULL;
  2831.         }
  2832.         
  2833.         $questionObject $quizHelper->getQuestionById($request->request->get("questionId"));
  2834.         if($questionObject->getType() == QuizQuestion::RADIO_BUTTONS) {
  2835.             $userAnswer $quizHelper->getOptionByID($request->request->get("question-$question"));
  2836.             $qoid $userAnswer['id'];
  2837.             $a $userAnswer['title'];
  2838.         }
  2839.         else {
  2840.             $qoid null;
  2841.             $a $request->request->get("question-$question");
  2842.         }
  2843.         $responseID $quizHelper->saveResponse($uid$nt$qid$questionObject->getId(), $qoid$a);
  2844.         
  2845.         $quiz $quizHelper->getQuizObjectBySlug($slug);
  2846.         if (in_array($slug, ["wdyfir""certainteed"]) && $question == $quizHelper->getLastQuestionNumberBySlug($slug)) {
  2847.             $ref $quizHelper->finishQuiz($responseID);
  2848.             if ($this->user) {
  2849.                 $email $this->user->getEmail();
  2850.                 $fname $this->user->getFirstName();
  2851.                 $lname $this->user->getLastName();
  2852.                 // need to add to mailchimp here too 
  2853.                 $mailChimpHelper->subscribe($email,
  2854.                     [
  2855.                         'FNAME'=>$fname,
  2856.                         'LNAME'=>$lname
  2857.                     ],
  2858.                     [
  2859.                         'WIR'
  2860.                     ]
  2861.                 );
  2862.                 $quizHelper->sendQuizResultsEmail($responseID);
  2863.                 return $this->redirectToRoute("Quiz-Results", [
  2864.                     "slug" => $slug,
  2865.                     "ref" => $ref
  2866.                 ]);
  2867.             }else{
  2868.                 return $this->redirectToRoute("Quiz-Lead", [
  2869.                     "slug" => $slug,
  2870.                     "ref" => $ref
  2871.                 ]);
  2872.             }
  2873.         }
  2874.         elseif(!in_array($slug, ["wdyfir""certainteed"]) && $question == $quiz->countQuizQuestions()) {
  2875.             //Dynamic Quizzes:
  2876.             $ref $quizHelper->finishQuiz($responseID);
  2877.             if ($this->user) {
  2878.                 $quizHelper->sendQuizResultsEmail($responseID$ref);
  2879.                 return $this->redirectToRoute("Quiz-Results", [
  2880.                     "slug" => $slug,
  2881.                     "ref" => $ref
  2882.                 ]);
  2883.             }
  2884.             else {
  2885.                 return $this->redirectToRoute("Quiz-Lead", [
  2886.                     "slug" => $slug,
  2887.                     "ref" => $ref
  2888.                 ]);
  2889.             }
  2890.         }
  2891.         else{
  2892.             return $this->redirectToRoute("Quick-Question", [
  2893.                 "slug" => $slug,
  2894.                 "question" => $question+1
  2895.             ]);
  2896.         }
  2897.     }
  2898.     /**
  2899.     * @Route("/quiz/{slug}/results/{ref}", name="Quiz-Results")
  2900.     */
  2901.     public function quizResults(
  2902.         Request $request,
  2903.         QuizHelper $quizHelper,
  2904.         $slug,
  2905.         $ref
  2906.     ){
  2907.         $quiz $quizHelper->getQuizObjectBySlug($slug);
  2908.         $results $quizHelper->getResultsByRef($ref);
  2909.         if(in_array($slug, ["wdyfir""certainteed"])) {
  2910.             return $this->defaultRender("content/quiz/$slug/ending.html.twig"$results);
  2911.         }
  2912.         $response $quizHelper->getQuizResponseByRefurl($ref);
  2913.         return $this->defaultRender("content/quiz/dynamic/ending.html.twig", [
  2914.             "quiz" => $quiz,
  2915.             "response" => $response,
  2916.             "result" => $response->getQuizResult()
  2917.         ]);
  2918.     }
  2919.     /**
  2920.     * @Route("/quizz/debugger", name="quiz-debugger")
  2921.     */
  2922.     public function quizDebugger(
  2923.         Request $request,
  2924.         QuizHelper $quizHelper
  2925.     ){
  2926.         return new JsonResponse($this->user->getLastname());
  2927.     }
  2928.     
  2929.     //TODO: move all ajax to different controllers
  2930.         
  2931.         /**
  2932.         * @Route("/ajax/social-data")
  2933.         */
  2934.         public function socialDataAjaxAction(
  2935.             Request $request,
  2936.             CustomerHelper $customerHelper
  2937.         ) {
  2938.             return new JsonResponse(json_encode(
  2939.                 [
  2940.                     "facebookHandles" => $customerHelper->getFacebookHandles(),
  2941.                     "linkedinHandles" => $customerHelper->getLinkedinHandles(),
  2942.                     "twitterHandles" => $customerHelper->getTwitterHandles(),
  2943.                     "tags" => $customerHelper->getCustomerTags()
  2944.                 ]
  2945.             ));
  2946.         }
  2947.         /**
  2948.         * @Route("/ajax/link")
  2949.         */
  2950.         public function linkAjaxAction(
  2951.             Request $request,
  2952.             MenuHelper $menuHelper,
  2953.             ContentHelper $contentHelper
  2954.         ) {
  2955.             if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {
  2956.                 $id $request->get("id");
  2957.                 $link $menuHelper->getLinkById($id);
  2958.                 if($link) {
  2959.                     $contentHelper->addImpression($request""$link);
  2960.                     return new JsonResponse($link->getRef());
  2961.                 }
  2962.             }
  2963.         }
  2964.         
  2965.         /**
  2966.         * @Route("/ajax/link-catchall")
  2967.         */
  2968.         public function linkCatchallAjaxAction(
  2969.             Request $request,
  2970.             ContentHelper $contentHelper
  2971.         ) {
  2972.             
  2973.             if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {
  2974.                 
  2975.                 $path $request->get("path");
  2976.                 $href $request->get("href");
  2977.                 
  2978.                 $entityManager $this->getDoctrine()->getManager();
  2979.                 $content $entityManager
  2980.                     ->getRepository(Content::class)
  2981.                     ->getContentByUrl(
  2982.                         $path,
  2983.                         $this->site_code
  2984.                     );
  2985.                     
  2986.                 //if($content) {
  2987.                     $contentHelper->addImpression($request$content"""""3"$href);
  2988.                     return new JsonResponse($content $content->getId() : null);
  2989.                 //}
  2990.                 
  2991.             }
  2992.             
  2993.         }
  2994.         
  2995.         /**
  2996.         * @Route("/ajax/mitem-click")
  2997.         */
  2998.         public function mitemClickAjaxAction(
  2999.             Request $request,
  3000.             MediaHelper $mediaHelper,
  3001.             ContentHelper $contentHelper
  3002.         ) {
  3003.             if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {
  3004.                 $id $request->get("id");
  3005.                 $item $mediaHelper->getMediaGroupItemById($id);
  3006.                 if($item) {
  3007.                     $contentHelper->addImpression($request""""$item2);
  3008.                     return new JsonResponse($item->getExternalUrl());
  3009.                 }
  3010.             }
  3011.         }
  3012.         /**
  3013.         * @Route("/ajax/mitem-impression")
  3014.         */
  3015.         public function mitemImpressionAjaxAction(
  3016.             Request $request,
  3017.             MediaHelper $mediaHelper,
  3018.             ContentHelper $contentHelper
  3019.         ) {
  3020.             if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {
  3021.                 $id $request->get("id");
  3022.                 $item $mediaHelper->getMediaGroupItemById($id);
  3023.                 if($item) {
  3024.                     $contentHelper->addImpression($request""""$item1);
  3025.                     return new JsonResponse($item->getExternalUrl());
  3026.                 }
  3027.             }
  3028.         }
  3029.         
  3030.         //New function for multiple impressions below
  3031.         
  3032.         /**
  3033.         * @Route("/ajax/mitem-impressions")
  3034.         */
  3035.         public function mitemImpressionsAjaxAction(
  3036.             Request $request,
  3037.             MediaHelper $mediaHelper,
  3038.             ContentHelper $contentHelper
  3039.         ) {
  3040.             if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {
  3041.                 
  3042.                 $ids $request->get("ids");
  3043.                 $return = [];
  3044.                 
  3045.                 foreach($ids as $id) {
  3046.                     $item $mediaHelper->getMediaGroupItemByIdOrNull($id);
  3047.                     if($item) {
  3048.                         $contentHelper->addImpression($request""""$item1);
  3049.                         $return[] = $item->getExternalUrl();
  3050.                     }
  3051.                 }
  3052.                 
  3053.                 return new JsonResponse($return);
  3054.             }
  3055.         }
  3056.         
  3057.         /**
  3058.         * @Route("/ajax/content-impressions")
  3059.         */
  3060.         public function contentImpressionsAjaxAction(
  3061.             Request $request,
  3062.             ContentHelper $contentHelper
  3063.         ) {
  3064.             
  3065.             $contentHelper->storeQueuedImpressions($request);
  3066.             return new JsonResponse("Content Impressions Stored");
  3067.             
  3068.         }
  3069.         /**
  3070.         * @Route("/ajax/like-content")
  3071.         */
  3072.         public function likeAjaxAction(
  3073.             Request $request,
  3074.             ContentHelper $helper
  3075.         ) {
  3076.             if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED') && ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1)) {
  3077.                 $id $request->get("id");
  3078.                 if($id) {
  3079.                     $content $helper->getContentById($id);
  3080.                     $helper->likeContent($content$this->getUser());
  3081.                     $likes $helper->countLikes($content);
  3082.                     $entityManager $this->getDoctrine()->getManager();
  3083.                     $entityManager->persist($content);
  3084.                     $entityManager->flush();
  3085.                     return new JsonResponse($likes);
  3086.                 }
  3087.                 else {
  3088.                     return null;
  3089.                 }
  3090.             } else {
  3091.             }
  3092.         }
  3093.         /**
  3094.         * @Route("/ajax/unlike-content")
  3095.         */
  3096.         public function unlikeAjaxAction(
  3097.             Request $request,
  3098.             ContentHelper $helper
  3099.         ) {
  3100.             if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED') && ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1)) {
  3101.                 $id $request->get("id");
  3102.                 if($id) {
  3103.                     $content $helper->getContentById($id);
  3104.                     $helper->unlikeContent($content$this->getUser());
  3105.                     $likes $helper->countLikes($content);
  3106.                     $entityManager $this->getDoctrine()->getManager();
  3107.                     $entityManager->persist($content);
  3108.                     $entityManager->flush();
  3109.                     return new JsonResponse($likes);
  3110.                 }
  3111.                 else {
  3112.                     return null;
  3113.                 }
  3114.             } else {
  3115.             }
  3116.         }
  3117.         /**
  3118.         * @Route("/ajax/forum-quote-content")
  3119.         */
  3120.         public function forumQuoteAjaxAction(
  3121.             Request $request,
  3122.             ContentHelper $helper
  3123.         ) {
  3124.             if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED') && ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1)) {
  3125.                 $id $request->get("id");
  3126.                 if($id) {
  3127.                     $content $helper->getContentById($id);
  3128.                     return new JsonResponse("<blockquote>".$content->getContentFull()."<br> -".$content->getAuthor()."</blockquote>");
  3129.                 }
  3130.                 else {
  3131.                     return null;
  3132.                 }
  3133.             } else {
  3134.             }
  3135.         }
  3136.         /**
  3137.         * @Route("/ajax/forum-images-upload")
  3138.         */
  3139.         public function forumUploadImage(
  3140.             Request $request,
  3141.             ContentHelper $helper
  3142.         ) {
  3143.             /*
  3144.             if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED') && ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1)) {
  3145.             $id = $request->get("id");
  3146.             return new JsonResponse("<blockquote>".$content->getContentFull()."<br> -".$content->getAuthor()."</blockquote>");
  3147.             }*/
  3148.             
  3149.             //$accepted_origins = array("http://localhost", "http://192.168.1.1", "http://example.com");
  3150.             
  3151.             $imageFolder "uploads/forum/";
  3152.             
  3153.             reset ($_FILES);
  3154.             $temp current($_FILES);
  3155.             if (is_uploaded_file($temp['tmp_name'])){
  3156.                 
  3157.                 // Sanitize input
  3158.                 if (preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/"$temp['name'])) {
  3159.                     return new JsonResponse(array('error' => "Invalid file name."));
  3160.                 }
  3161.                 
  3162.                 // Verify extension
  3163.                 if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif""jpg""png"))) {
  3164.                     return new JsonResponse(array('error' => "Invalid file type."));
  3165.                 }
  3166.                 
  3167.                 // Make a unique filename
  3168.                 $filename pathinfo($temp['name'], PATHINFO_FILENAME );
  3169.                 $ext pathinfo($temp['name'], PATHINFO_EXTENSION);
  3170.                 
  3171.                 $filename trim(trim(strtolower($filename)), '-');
  3172.                 $filename str_replace(' ''-'$filename);
  3173.                 $filename preg_replace('/-+/''-'$filename);
  3174.                 $filename preg_replace('/[^a-z0-9-]/'''$filename);
  3175.                 
  3176.                 $final_filename $filename "." $ext;
  3177.                 $x 2;
  3178.                 while(file_exists($imageFolder $final_filename)) {
  3179.                     $final_filename $filename '-' $x++ . "." $ext;
  3180.                 }
  3181.                 
  3182.                 // Accept upload if there was no origin, or if it is an accepted origin
  3183.                 $filetowrite $imageFolder $final_filename;
  3184.                 move_uploaded_file($temp['tmp_name'], $filetowrite);
  3185.                 
  3186.                 //$filetowrite = $imageFolder . $temp['name'];
  3187.                 //move_uploaded_file($temp['tmp_name'], $filetowrite);
  3188.                 
  3189.                 // Respond to the successful upload with JSON.
  3190.                 // Use a location key to specify the path to the saved image resource.
  3191.                 return new JsonResponse(array('location' => "/".$filetowrite));
  3192.             } else {
  3193.                 // Notify editor that the upload failed
  3194.                 return new JsonResponse(array('error' => "500 Server Error."));
  3195.             }
  3196.             
  3197.         }
  3198.         
  3199.         /**
  3200.         * @Route("/ajax/ckeditor-image-upload")
  3201.         */
  3202.         public function ckeditorUploadImage(
  3203.             Request $request,
  3204.             ContentHelper $helper
  3205.         ) {
  3206.             
  3207.             if ($request->files->get("upload")) { //image field
  3208.                 
  3209.                 $uploaded_image $request->files->get("upload");
  3210.                 
  3211.                 $mime $uploaded_image->getMimeType();
  3212.                 if(!in_array($mime, ["image/jpg""image/jpeg""image/png""image/gif"])) {
  3213.                     return new JsonResponse(array('error' => "Only PNG, JPG, and GIF file types are allowed."));
  3214.                 }
  3215.                 
  3216.                 $media = new Media();
  3217.                 $media->setTitle(pathinfo($uploaded_image->getClientOriginalName(), PATHINFO_FILENAME));
  3218.                 $media->setData($uploaded_image);
  3219.                 $media->setDescription("Image uploaded through CKEditor.");
  3220.                 $media->setName($uploaded_image->getClientOriginalName());
  3221.                 
  3222.                 $entityManager $this->getDoctrine()->getManager();
  3223.                 $entityManager->persist($media);
  3224.                 $entityManager->flush();
  3225.                 
  3226.                 return new JsonResponse(array('url' => $media->getURL()));
  3227.             } else {
  3228.                 // Notify editor that the upload failed
  3229.                 return new JsonResponse(array('error' => "500 Server Error."));
  3230.             }
  3231.             
  3232.         }
  3233.         /**
  3234.         * @Route("/ajax/get-user-lead-info")
  3235.         */
  3236.         public function getUserLeadInfoAjaxAction(
  3237.             Request $request,
  3238.             ContentHelper $helper
  3239.         ) {
  3240.             if($this->user && ($this->user->isMember() || $this->user->isAdmin())) {
  3241.                 
  3242.                 $lead["firstname"] = $this->user->getUserMetaValueByKey("lead_firstname");
  3243.                 $lead["lastname"] = $this->user->getUserMetaValueByKey("lead_lastname");
  3244.                 $lead["company"] = $this->user->getUserMetaValueByKey("lead_company");
  3245.                 $lead["phone"] = $this->user->getUserMetaValueByKey("lead_phone");
  3246.                 $lead["email"] = $this->user->getUserMetaValueByKey("lead_email");
  3247.                 $lead["address1"] = $this->user->getUserMetaValueByKey("lead_address1");
  3248.                 $lead["address2"] = $this->user->getUserMetaValueByKey("lead_address2");
  3249.                 $lead["city"] = $this->user->getUserMetaValueByKey("lead_city");
  3250.                 $lead["state"] = $this->user->getUserMetaValueByKey("lead_state");
  3251.                 $lead["zip"] = $this->user->getUserMetaValueByKey("lead_zip");
  3252.                 $lead["country"] = $this->user->getUserMetaValueByKey("lead_country");
  3253.                 $lead["country_other"] = $this->user->getUserMetaValueByKey("lead_country_other");
  3254.                 $lead["contractor_type"] = $this->user->getUserMetaValueByKey("lead_contractor_type");
  3255.                 $lead["business_type"] = $this->user->getUserMetaValueByKey("lead_business_type");
  3256.                 
  3257.                 return new JsonResponse(json_encode($lead));
  3258.                 
  3259.             } else {
  3260.                 return new JsonResponse("");
  3261.             }
  3262.         }
  3263.         
  3264.         /**
  3265.         * @Route("/ajax/setSessionVariable")
  3266.         */
  3267.         public function setSessionVariableAjaxAction(
  3268.             Request $request
  3269.         ) {
  3270.             
  3271.             if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {
  3272.                 
  3273.                 $key $request->get("key");
  3274.                 $value $request->get("value");
  3275.                 
  3276.                 if($key) {
  3277.                     $session $request->getSession();
  3278.                     
  3279.                     if($value) {
  3280.                         $session->set($key$value);
  3281.                     }
  3282.                     else {
  3283.                         $session->remove($key);
  3284.                     }
  3285.                     
  3286.                     return new JsonResponse("Session variable set.");
  3287.                 }
  3288.                 
  3289.             }
  3290.             
  3291.             return new JsonResponse("Session variable set.");
  3292.             
  3293.         }
  3294.         
  3295.         /**
  3296.         * @Route("/pollExport/{pollId}", name="poll_export")
  3297.         */
  3298.         public function pollExport(
  3299.             Request $request,
  3300.             PollHelper $pollHelper,
  3301.             $pollId ""
  3302.         ) {
  3303.             
  3304.             $access false;
  3305.             if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  3306.                 $user $this->getUser();
  3307.                 if($user) {
  3308.                     if($this->user->isAdmin()) {
  3309.                         $access true;
  3310.                     }
  3311.                 }
  3312.             }
  3313.             
  3314.             $poll $pollHelper->getPollById($pollId);
  3315.             $pollOptions $poll->getPollOptions();
  3316.             $pollResponses $poll->getPollResponses();
  3317.             
  3318.             //Export / Spreadsheet
  3319.             $spreadsheet = new Spreadsheet();
  3320.             
  3321.             $spreadsheet = new Spreadsheet();
  3322.             $sheet $spreadsheet->getActiveSheet();
  3323.             
  3324.             //Sheet 1
  3325.             $rowNum 1;
  3326.             $sheet->setTitle("Poll Results");
  3327.             $sheet->setCellValue("A{$rowNum}""Poll Option");
  3328.             $sheet->setCellValue("B{$rowNum}""Votes");
  3329.             $sheet->getStyle("A{$rowNum}")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFDDDDDD');
  3330.             $sheet->getStyle("B{$rowNum}")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFDDDDDD');
  3331.             $rowNum++;
  3332.             
  3333.             foreach($pollOptions as $pollOption) {
  3334.                 $sheet->setCellValue("A{$rowNum}"$pollOption->getText());
  3335.                 $sheet->setCellValue("B{$rowNum}"$pollOption->countResponses());
  3336.                 $rowNum++;
  3337.             }
  3338.             $sheet->setCellValue("A{$rowNum}""Total:");
  3339.             $sheet->setCellValue("B{$rowNum}"$poll->countResponses());
  3340.             $sheet->getStyle("A{$rowNum}")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFDDDDDD');
  3341.             $sheet->getStyle("B{$rowNum}")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFDDDDDD');
  3342.             
  3343.             foreach(range("A",$sheet->getHighestColumn()) as $columnID) {
  3344.                 $sheet->getColumnDimension($columnID)
  3345.                     ->setAutoSize(true);
  3346.             }
  3347.             
  3348.             //Sheet 2
  3349.             $indSheet = new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet'Individual Votes');
  3350.             $spreadsheet->addSheet($indSheet0);
  3351.             
  3352.             $rowNum 1;
  3353.             $indSheet->setTitle("Individual Votes");
  3354.             $indSheet->setCellValue("A{$rowNum}""User");
  3355.             $indSheet->setCellValue("B{$rowNum}""Vote");
  3356.             $indSheet->getStyle("A{$rowNum}")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFDDDDDD');
  3357.             $indSheet->getStyle("B{$rowNum}")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFDDDDDD');
  3358.             $rowNum++;
  3359.             
  3360.             foreach($pollResponses as $pollResponse) {
  3361.                 $indSheet->setCellValue("A{$rowNum}"$pollResponse->getUser() ? $pollResponse->getUser() : "anonymous");
  3362.                 $indSheet->setCellValue("B{$rowNum}"$pollResponse->getPollOption());
  3363.                 $rowNum++;
  3364.             }
  3365.             
  3366.             foreach(range("A",$indSheet->getHighestColumn()) as $columnID) {
  3367.                 $indSheet->getColumnDimension($columnID)
  3368.                     ->setAutoSize(true);
  3369.             }
  3370.             
  3371.             //Finish and save
  3372.             $spreadsheet->setActiveSheetIndexByName("Poll Results");
  3373.             $writer = new Xlsx($spreadsheet);
  3374.             $filename "Poll Export {$pollId}.xlsx";
  3375.             $writer->save("../var/reports/polls/{$filename}");
  3376.             
  3377.             //return new JsonResponse($filename . " saved");
  3378.             
  3379.             //$filename = $request->request->get("filename");
  3380.             $response = new BinaryFileResponse("../var/reports/polls/{$filename}");
  3381.             $disposition $response->headers->makeDisposition(
  3382.                 ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  3383.                 $filename
  3384.             );
  3385.             $response->headers->set('Content-Disposition'$disposition);
  3386.             return $response;
  3387.         }
  3388.         /**
  3389.         * @Route("/ajax/pollResponse")
  3390.         */
  3391.         public function addPollResponse(
  3392.             Request $request,
  3393.             PollHelper $pollHelper
  3394.         ) {
  3395.             
  3396.             if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {
  3397.                 
  3398.                 $pollId $request->get("pollId");
  3399.                 $pollOptionId $request->get("pollOptionId");
  3400.                 $userId $request->get("userId");
  3401.                 
  3402.                 if($pollOptionId) {
  3403.                     $pollHelper->addPollResponse($pollOptionId$userId $userId NULL);
  3404.                     $results $pollHelper->getPollResults($pollId);
  3405.                     //$results = implode(" ", $pollHelper->getPollResults($pollId));
  3406.                     return new JsonResponse($results);
  3407.                 }
  3408.                 
  3409.             }
  3410.             
  3411.             return new JsonResponse("Failure.");
  3412.             
  3413.         }
  3414.         
  3415.         /**
  3416.         * @Route("/ajax/pollResults")
  3417.         */
  3418.         public function getpollResultsAjax(
  3419.             Request $request,
  3420.             PollHelper $pollHelper,
  3421.             Environment $twig,
  3422.             $id ""
  3423.         ) {
  3424.             try {
  3425.                 $id $request->get("id");
  3426.                 
  3427.                 $poll $pollHelper->getPollById($id);
  3428.                 
  3429.                 $tmpl $twig->load("polls/admin-poll-results-embed.html.twig");
  3430.                 $html $tmpl->render(
  3431.                 [
  3432.                     "poll" => $poll
  3433.                 ]);
  3434.                 
  3435.                 return new JsonResponse($html);
  3436.             }
  3437.             catch (\Exception $e) {
  3438.                 return new JsonResponse("<div>Error loading poll results.</div>");
  3439.                 //return new JsonResponse($e->getMessage());
  3440.             }
  3441.             
  3442.         }
  3443.         /**
  3444.         * @Route("/ajax/quizResults")
  3445.         */
  3446.         public function getQuizResultsAjax(
  3447.             Request $request,
  3448.             QuizHelper $quizHelper,
  3449.             Environment $twig,
  3450.             $id ""
  3451.         ) {
  3452.             try {
  3453.                 $id $request->get("id");
  3454.                 
  3455.                 $quiz $quizHelper->getQuizById($id);
  3456.                 
  3457.                 $tmpl $twig->load("quizzes/admin-quiz-results-embed.html.twig");
  3458.                 $html $tmpl->render(
  3459.                 [
  3460.                     "quiz" => $quiz
  3461.                 ]);
  3462.                 
  3463.                 return new JsonResponse($html);
  3464.             }
  3465.             catch (\Exception $e) {
  3466.                 return new JsonResponse("<div>Error loading quiz results.</div>");
  3467.             }
  3468.             
  3469.         }
  3470.         /**
  3471.         * @Route("/ajax/contentUserViews")
  3472.         */
  3473.         public function getContentUserViews(
  3474.             Request $request,
  3475.             ContentHelper $contentHelper,
  3476.             Environment $twig,
  3477.             $id ""
  3478.         ) {
  3479.             //return false;
  3480.             try {
  3481.                 $id $request->get("id");
  3482.                 $content $contentHelper->getContentById($id);
  3483.                 $entityManager $this->getDoctrine()->getManager();
  3484.                 //TODO: Make a service for this
  3485.                 
  3486.                 //Google Analytics
  3487.                 $year date("Y");
  3488.                 $month date("n");
  3489.                 //$startDate = date("Y-m-d", strtotime($year."-".$month."-"."01"));
  3490.                 $startDate date("Y-m-d"strtotime("2020-10-"."01")); //when we started using this custom dimension
  3491.                 //$startDate = new \DateTime($startDate);
  3492.                 $endDate date("Y-m-t"strtotime($year."-".$month."-01"));
  3493.                 //$endDate = new \DateTime($endDate." 23:59:59");
  3494.                 
  3495.                 $client = new \Google_Client();
  3496.                 $client->setApplicationName("RCS Analytic Reports");
  3497.                 $KEY_FILE_LOCATION __DIR__ '/../RCS/RCS-AnalyticReports-9cf5364bc460.json';
  3498.                 $client->setAuthConfig($KEY_FILE_LOCATION);
  3499.                 $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
  3500.                 $analytics = new \Google_Service_AnalyticsReporting($client);
  3501.                 $dateRange = new \Google_Service_AnalyticsReporting_DateRange();
  3502.                 $dateRange->setStartDate($startDate);
  3503.                 $dateRange->setEndDate($endDate);
  3504.                 $views = new \Google_Service_AnalyticsReporting_Metric();
  3505.                 $views->setExpression("ga:pageviews");
  3506.                 $views->setAlias("pageviews");
  3507.                 $path = new \Google_Service_AnalyticsReporting_Dimension();
  3508.                 $path->setName("ga:pagePath");
  3509.                 $rcsUserID = new \Google_Service_AnalyticsReporting_Dimension();
  3510.                 $rcsUserID->setName("ga:dimension2");
  3511.                 
  3512.                 // Create the DimensionFilter.
  3513.                 $dimensionFilter = new \Google_Service_AnalyticsReporting_DimensionFilter();
  3514.                 
  3515.                 //Should be faster. Need to set for each job.
  3516.                 $dimensionFilter->setDimensionName('ga:pagePath');
  3517.                 $dimensionFilter->setOperator('IN_LIST');
  3518.                 $dimensionFilter->setExpressions([$content->getURL(1)]);
  3519.                 //$dimensionFilter->setExpressions(["/news-room"]);
  3520.                 
  3521.                 // Create the DimensionFilterClauses
  3522.                 $dimensionFilterClause = new \Google_Service_AnalyticsReporting_DimensionFilterClause();
  3523.                 $dimensionFilterClause->setFilters(array($dimensionFilter));
  3524.                 $request = new \Google_Service_AnalyticsReporting_ReportRequest();
  3525.                 $request->setViewId("126182454"); //< Unfiltered Website Data
  3526.                 $request->setDateRanges($dateRange);
  3527.                 $request->setDimensions(array($path$rcsUserID));
  3528.                 $request->setDimensionFilterClauses(array($dimensionFilterClause));
  3529.                 $request->setMetrics(array($views));
  3530.                 $request->setPageSize("10000");
  3531.                 //$request->setPageSize("10");
  3532.                 
  3533.                 $order = new \Google_Service_AnalyticsReporting_OrderBy;
  3534.                 $order->setFieldName("ga:pageviews");
  3535.                 $order->setOrderType("VALUE");
  3536.                 $order->setSortOrder("DESCENDING");
  3537.                 $orders[] = $order;
  3538.                 $request->setOrderBys($orders);
  3539.                 $body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
  3540.                 $body->setReportRequests(array($request));
  3541.                 $reports $analytics->reports->batchGet($body);
  3542.                 
  3543.                 
  3544.                 $data = [];
  3545.                 for ($reportIndex 0$reportIndex count($reports); $reportIndex++) {
  3546.                     $report $reports[$reportIndex];
  3547.                     $header $report->getColumnHeader();
  3548.                     $dimensionHeaders $header->getDimensions();
  3549.                     $metricHeaders $header->getMetricHeader()->getMetricHeaderEntries();
  3550.                     $rows $report->getData()->getRows();
  3551.                     for ($rowIndex 0$rowIndex count($rows); $rowIndex++) {
  3552.                         $row $rows[$rowIndex];
  3553.                         $dimensions $row->getDimensions();
  3554.                         $metrics $row->getMetrics();
  3555.                         $path "";
  3556.                         $rcsUserID "";
  3557.                         $count 0;
  3558.                         for ($i 0$i count($dimensionHeaders) && $i count($dimensions); $i++) {
  3559.                             
  3560.                             if ($dimensionHeaders[$i] == "ga:pagePath") {
  3561.                                 $path $dimensions[$i];
  3562.                             }
  3563.                             if ($dimensionHeaders[$i] == "ga:dimension2") {
  3564.                                 $rcsUserID $dimensions[$i];
  3565.                             }
  3566.                         }
  3567.                         
  3568.                         $count $metrics[0]->getValues()[0];
  3569.                         
  3570.                         
  3571.                         //strip any url parameters
  3572.                         //$path = strtok($path, "?");
  3573.                         //for ($j = 0; $j < count($metricHeaders) && $j < count($metrics); $j++) {
  3574.                         //    $entry = $metricHeaders[$j];
  3575.                         //    $values = $metrics[$j];
  3576.                         //    for ($valueIndex = 0; $valueIndex < count($values->getValues()); $valueIndex++) {
  3577.                         //        $value = $values->getValues()[$valueIndex];
  3578.                         //        $count = $value;
  3579.                         //    }
  3580.                         //}
  3581.                         
  3582.                         //if (!isset($data[$path])) {
  3583.                         //    $data[$path] = array();
  3584.                         //}
  3585.                         //if (!isset($data[$path][$rcsUserID])) {
  3586.                         //    $data[$path][$rcsUserID] = $count;
  3587.                         //}
  3588.                         //else {
  3589.                         //    $data[$path][$rcsUserID] += $count;
  3590.                         //}
  3591.                         
  3592.                         if (!isset($data[$rcsUserID])) {
  3593.                             $user $entityManager
  3594.                                 ->getRepository(User::class)
  3595.                                 ->findOneBy(["id" => $rcsUserID]);
  3596.                             $data[$rcsUserID] = ["views" => $count"user" => $user];
  3597.                         }
  3598.                     }
  3599.                 }
  3600.                 foreach($data as $key => $value) {
  3601.                     
  3602.                     /*
  3603.                     if($key == "/") { continue; }
  3604.                     
  3605.                     $pos = strrpos($key, '/');
  3606.                     $slug = $pos === false ? $key : substr($key, $pos + 1);
  3607.                     
  3608.                     $arr = explode("?", $slug, 2);
  3609.                     $slug = $arr[0];
  3610.                     
  3611.                     if(!$slug) { continue; }
  3612.                     $content = $entityManager
  3613.                         ->getRepository(Content::class)
  3614.                         ->findOneBy(["slug" => $slug]);
  3615.                     
  3616.                     if($content) {
  3617.                         $edit_links[$key] = "/admin/content/". $content->getId() . "/edit";
  3618.                         //TODO: Handle switching sites when editing.
  3619.                         //$edit_links[$key] = "/admin/content/". $content->getId() . "/edit?site=". $content->getSite();
  3620.                     }
  3621.                     */
  3622.                 }
  3623.                 
  3624.                 //Just copying above code for single week to get up in time for the meeting. Will clean up later.
  3625.                 $year date("Y");
  3626.                 $month date("n");
  3627.                 $day date("d");
  3628.                 
  3629.                 $startDate date('Y-m-d'strtotime('-1 week'));
  3630.                 $endDate date("Y-m-d");
  3631.                 
  3632.                 $client = new \Google_Client();
  3633.                 $client->setApplicationName("RCS Analytic Reports");
  3634.                 $KEY_FILE_LOCATION __DIR__ '/../RCS/RCS-AnalyticReports-9cf5364bc460.json';
  3635.                 $client->setAuthConfig($KEY_FILE_LOCATION);
  3636.                 $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
  3637.                 $analytics = new \Google_Service_AnalyticsReporting($client);
  3638.                 $dateRange = new \Google_Service_AnalyticsReporting_DateRange();
  3639.                 $dateRange->setStartDate($startDate);
  3640.                 $dateRange->setEndDate($endDate);
  3641.                 $views = new \Google_Service_AnalyticsReporting_Metric();
  3642.                 $views->setExpression("ga:pageviews");
  3643.                 $views->setAlias("pageviews");
  3644.                 $path = new \Google_Service_AnalyticsReporting_Dimension();
  3645.                 $path->setName("ga:pagePath");
  3646.                 $rcsUserID = new \Google_Service_AnalyticsReporting_Dimension();
  3647.                 $rcsUserID->setName("ga:dimension2");
  3648.                 
  3649.                 $dimensionFilter = new \Google_Service_AnalyticsReporting_DimensionFilter();
  3650.                 
  3651.                 $dimensionFilter->setDimensionName('ga:pagePath');
  3652.                 $dimensionFilter->setOperator('IN_LIST');
  3653.                 $dimensionFilter->setExpressions([$content->getURL(1)]);
  3654.                 
  3655.                 // Create the DimensionFilterClauses
  3656.                 $dimensionFilterClause = new \Google_Service_AnalyticsReporting_DimensionFilterClause();
  3657.                 $dimensionFilterClause->setFilters(array($dimensionFilter));
  3658.                 $request = new \Google_Service_AnalyticsReporting_ReportRequest();
  3659.                 $request->setViewId("126182454"); //< Unfiltered Website Data
  3660.                 $request->setDateRanges($dateRange);
  3661.                 $request->setDimensions(array($path$rcsUserID));
  3662.                 $request->setDimensionFilterClauses(array($dimensionFilterClause));
  3663.                 $request->setMetrics(array($views));
  3664.                 $request->setPageSize("10000");
  3665.                 //$request->setPageSize("10");
  3666.                 
  3667.                 $order = new \Google_Service_AnalyticsReporting_OrderBy;
  3668.                 $order->setFieldName("ga:pageviews");
  3669.                 $order->setOrderType("VALUE");
  3670.                 $order->setSortOrder("DESCENDING");
  3671.                 $orders[] = $order;
  3672.                 $request->setOrderBys($orders);
  3673.                 $body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
  3674.                 $body->setReportRequests(array($request));
  3675.                 $reports $analytics->reports->batchGet($body);
  3676.                 
  3677.                 
  3678.                 $dataweek = [];
  3679.                 for ($reportIndex 0$reportIndex count($reports); $reportIndex++) {
  3680.                     $report $reports[$reportIndex];
  3681.                     $header $report->getColumnHeader();
  3682.                     $dimensionHeaders $header->getDimensions();
  3683.                     $metricHeaders $header->getMetricHeader()->getMetricHeaderEntries();
  3684.                     $rows $report->getData()->getRows();
  3685.                     for ($rowIndex 0$rowIndex count($rows); $rowIndex++) {
  3686.                         $row $rows[$rowIndex];
  3687.                         $dimensions $row->getDimensions();
  3688.                         $metrics $row->getMetrics();
  3689.                         $path "";
  3690.                         $rcsUserID "";
  3691.                         $count 0;
  3692.                         for ($i 0$i count($dimensionHeaders) && $i count($dimensions); $i++) {
  3693.                             
  3694.                             if ($dimensionHeaders[$i] == "ga:pagePath") {
  3695.                                 $path $dimensions[$i];
  3696.                             }
  3697.                             if ($dimensionHeaders[$i] == "ga:dimension2") {
  3698.                                 $rcsUserID $dimensions[$i];
  3699.                             }
  3700.                         }
  3701.                         $count $metrics[0]->getValues()[0];
  3702.                         
  3703.                         if (!isset($dataweek[$rcsUserID])) {
  3704.                             $user $entityManager
  3705.                                 ->getRepository(User::class)
  3706.                                 ->findOneBy(["id" => $rcsUserID]);
  3707.                             $dataweek[$rcsUserID] = ["views" => $count"user" => $user];
  3708.                         }
  3709.                     }
  3710.                 }
  3711.                 
  3712.                 $tmpl $twig->load("sonata_admin/content-user-views-embed.html.twig");
  3713.                 $html $tmpl->render(
  3714.                 [
  3715.                     "content" => $content,
  3716.                     "data" => $data,
  3717.                     "dataweek" => $dataweek,
  3718.                     //"rows" => $rows,
  3719.                 ]);
  3720.                 
  3721.                 return new JsonResponse($html);
  3722.             }
  3723.             catch (\Exception $e) {
  3724.                 //return new JsonResponse("<div>Error loading results.</div>");
  3725.                 return new JsonResponse($e->getMessage());
  3726.             }
  3727.             
  3728.         }
  3729.         /**
  3730.         * @Route("/ajax/accept-cookies")
  3731.         */
  3732.         public function acceptCookiesAjaxAction(
  3733.             Request $request
  3734.         ) {
  3735.             if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {
  3736.                 $user $this->user;
  3737.                 if($user) {
  3738.                     $user->setUsermetum("acceptCookies""1");
  3739.                     $entityManager $this->getDoctrine()->getManager();
  3740.                     $entityManager->persist($user);
  3741.                     $entityManager->flush();
  3742.                     return new JsonResponse("1");
  3743.                 }
  3744.             }
  3745.             return new JsonResponse("0");
  3746.         }
  3747.         
  3748.         /**
  3749.         * @Route("/ajax/set-preferred-language")
  3750.         */
  3751.         public function preferredLanguageAjaxAction(
  3752.             Request $request
  3753.         ) {
  3754.             
  3755.             if ($request->isXmlHttpRequest() || $request->query->get('showJson') == 1) {
  3756.                 $user $this->user;
  3757.                 $language $request->get("language");
  3758.                 if($user && $language) {
  3759.                     $contact $user->getContact();
  3760.                     if($contact) {
  3761.                         $contact->setPreferredLanguage($language);
  3762.                         $entityManager $this->getDoctrine()->getManager();
  3763.                         $entityManager->persist($contact);
  3764.                         $entityManager->flush();
  3765.                         return new JsonResponse("1");
  3766.                     }
  3767.                 }
  3768.             }
  3769.             return new JsonResponse("0");
  3770.             
  3771.         }
  3772.         // @Route("/testtesttest", methods={"POST"})
  3773.         
  3774.         /**
  3775.         * @Route("/testtesttesths")
  3776.         */
  3777.         public function testtesttesths(
  3778.             Request $request,
  3779.             ContentHelper $contentHelper,
  3780.             CustomerHelper $customerHelper,
  3781.             HootsuiteHelper $hootsuiteHelper
  3782.         ) {    
  3783.             // get image from post request
  3784.             // $image = $request->files->get("image");
  3785.             // $imgObj = [
  3786.             //     "image" => $image->getPathname(),
  3787.             //     "mime" => $image->getMimeType(),
  3788.             //     "size" => $image->getSize(),
  3789.             // ];
  3790.             // $respUploadCreate = $hootsuiteHelper->createMediaUploadUri($imgObj);
  3791.             // $respUploadCreate = json_decode($respUploadCreate, true);
  3792.             // $respUploadCreate = $respUploadCreate['data'];
  3793.             // $respUpload = $hootsuiteHelper->uploadMedia($respUploadCreate['uploadUrl'], $imgObj);
  3794.             // sleep(5); // waiting to be sure that it's ready
  3795.             // $uploaded = $hootsuiteHelper->confirmMediaUpload($respUploadCreate['id']);
  3796.             // $resp = [
  3797.             //     "uploadCreate" => $respUploadCreate,
  3798.             //     "upload" => $uploaded,
  3799.             // ];
  3800.             //$resp = $hootsuiteHelper->schedulePost("Test post from RCS \n\n\n@AskARooferRCS ", [$respUploadCreate['id']], [125189773], "2025-01-01T12:12:00Z");
  3801.             //$resp = $hootsuiteHelper->schedulePost("Test post from RCS \n\n\n@AskARooferRCS ", [], [125189773, 7563642], "2025-01-01T12:12:00Z");
  3802.             return $this->defaultRender("test.html.twig", [
  3803.                 //"data" => json_decode($resp)
  3804.             ]);
  3805.         
  3806.             
  3807.             // $code = "q_muwsc8MGw2zqzDnrn37pj4GcVWYrXCVU5o9fsPr0E.ck04oiLoHqmDPSI5TD0va63-qFf_PYa4WJcZmRpwWK4";
  3808.             // $resp = $hootsuiteHelper->getMessage(12882399827);
  3809.             // schedulePost
  3810.             // $resp = $hootsuiteHelper->getSocialProfiles();
  3811.             //$hootsuiteHelper->updateSocialProfiles();
  3812.             // return new JsonResponse(json_encode(print_r($resp)), 200, [], true);
  3813.             // return new JsonResponse($tokens);
  3814.             //return new JsonResponse("testtestteset");
  3815.             
  3816.         }
  3817.         /**
  3818.         * @Route("/testtesttestga")
  3819.         */
  3820.         public function testtesttestga(
  3821.             Request $request,
  3822.             ContentHelper $contentHelper,
  3823.             CustomerHelper $customerHelper
  3824.         ) {
  3825.             //return false;
  3826.             //try {
  3827.             
  3828.                 set_time_limit(600);
  3829.                 
  3830.                 /*
  3831.                 $slug = $request->get("slug");
  3832.                 if(!$slug) {
  3833.                     throw new \Exception('Invalid directory.');
  3834.                 }
  3835.                 */
  3836.                 
  3837.                 if($request->request->has("date_start") && $request->request->has("date_end")
  3838.                     && $request->request->get("date_start") && $request->request->get("date_end")) {
  3839.                     $startDate date("Y-m-d"strtotime($request->request->get("date_start")));
  3840.                     $startDate = new \DateTime($startDate);
  3841.                     
  3842.                     $endDate date("Y-m-d"strtotime($request->request->get("date_end")));
  3843.                     $endDate = new \DateTime($endDate." 23:59:59");
  3844.                 }
  3845.                 elseif($request->request->has("date_start_current") && $request->request->has("date_end_current")
  3846.                     && $request->request->get("date_start_current") && $request->request->get("date_end_current")) {
  3847.                     $startDate date("Y-m-d"strtotime($request->request->get("date_start_current")));
  3848.                     $startDate = new \DateTime($startDate);
  3849.                     
  3850.                     $endDate date("Y-m-d"strtotime($request->request->get("date_end_current")));
  3851.                     $endDate = new \DateTime($endDate." 23:59:59");
  3852.                 }
  3853.                 else {
  3854.                     $year date("Y");
  3855.                     $month date("n");
  3856.                     
  3857.                     $startDate date("Y-m-d"strtotime($year."-".$month."-"."01"));
  3858.                     $startDate = new \DateTime($startDate);
  3859.                     $endDate date("Y-m-t"strtotime($year."-".$month."-"."01"));
  3860.                     $endDate = new \DateTime($endDate." 23:59:59");
  3861.                 }
  3862.                 
  3863.                 
  3864.                 $data =[];
  3865.                 foreach(SiteConfig::CONFIGS as $site_config) {
  3866.                     
  3867.                     if($site_config["id"] != 1/*!isset($site_config["ga_view_id"])*/) {
  3868.                         continue;
  3869.                     }
  3870.     
  3871.                     // 3/14/2019 removing source...
  3872.                     $client = new \Google_Client();
  3873.                     $client->setApplicationName("RCS Analytic Reports");
  3874.                     //$KEY_FILE_LOCATION = __DIR__ . '/My Project-4e8eeee2693a.json';
  3875.                     $KEY_FILE_LOCATION __DIR__ '/../RCS/RCS-AnalyticReports-9cf5364bc460.json';
  3876.                     //$KEY_FILE_LOCATION = __DIR__ . '/' . $site_config["analytics_key_file"];
  3877.                     $client->setAuthConfig($KEY_FILE_LOCATION);
  3878.                     $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
  3879.     
  3880.                     $analytics = new \Google_Service_AnalyticsReporting($client);
  3881.                     $dateRange = new \Google_Service_AnalyticsReporting_DateRange();
  3882.                     $dateRange->setStartDate($startDate->format('Y-m-d'));
  3883.                     $dateRange->setEndDate($endDate->format('Y-m-d'));
  3884.     
  3885.                     $avgTimeOnPage = new \Google_Service_AnalyticsReporting_Metric();
  3886.                     $avgTimeOnPage->setExpression("ga:avgTimeOnPage");
  3887.                     $avgTimeOnPage->setAlias("avgTimeOnPage");
  3888.     
  3889.                     $path = new \Google_Service_AnalyticsReporting_Dimension();
  3890.                     $path->setName("ga:pagePath");
  3891.     
  3892.                     //$medium = new \Google_Service_AnalyticsReporting_Dimension();
  3893.                     //$medium->setName("ga:medium");
  3894.     
  3895.     
  3896.                     $request = new \Google_Service_AnalyticsReporting_ReportRequest();
  3897.                     //$request->setViewId("126182454"); //< Unfiltered Website Data
  3898.                     $request->setViewId($site_config["ga_view_id"]); //< Unfiltered Website Data
  3899.                     $request->setDateRanges($dateRange);
  3900.                     $request->setDimensions(array($path));
  3901.                     //$request->setDimensions(array($path, $medium));
  3902.                     $request->setMetrics(array($avgTimeOnPage));
  3903.     
  3904.                     $request->setPageSize("10000");
  3905.     
  3906.                     $body = new \Google_Service_AnalyticsReporting_GetReportsRequest();
  3907.                     $body->setReportRequests(array($request));
  3908.                     $reports $analytics->reports->batchGet($body);
  3909.                     
  3910.     
  3911.     
  3912.                     /*
  3913.                     //If we ever have more than 10,000 results, we'll need to filter them or do something like this
  3914.     
  3915.                     // Remove count if you really want everything.
  3916.                     $cnt = 0;
  3917.                     while ($reports->reports[0]->nextPageToken > 0 && $cnt < 10) {
  3918.                         $body->reportRequests[0]->setPageToken($reports->reports[0]->nextPageToken);
  3919.                         $reports = $analytics->reports->batchGet( $body );
  3920.                         $cnt++;
  3921.                     }
  3922.                     */
  3923.     
  3924.                     
  3925.                     // 3/13/2019 removing source
  3926.                     $data[$site_config['id']] = [];
  3927.     
  3928.                     for ($reportIndex 0$reportIndex count($reports); $reportIndex++) {
  3929.                         $report $reports[$reportIndex];
  3930.                         $header $report->getColumnHeader();
  3931.                         $dimensionHeaders $header->getDimensions();
  3932.                         $metricHeaders $header->getMetricHeader()->getMetricHeaderEntries();
  3933.                         $rows $report->getData()->getRows();
  3934.     
  3935.                         for ($rowIndex 0$rowIndex count($rows); $rowIndex++) {
  3936.                             $row $rows[$rowIndex];
  3937.                             $dimensions $row->getDimensions();
  3938.                             $metrics $row->getMetrics();
  3939.     
  3940.                             $path "";
  3941.                             //$medium = "";
  3942.                             $count 0;
  3943.     
  3944.                             for ($i 0$i count($dimensionHeaders) && $i count($dimensions); $i++) {
  3945.     
  3946.                                 if ($dimensionHeaders[$i] == "ga:pagePath") {
  3947.                                     $path $dimensions[$i];
  3948.                                 }
  3949.     
  3950.                                 /*if ($dimensionHeaders[$i] == "ga:medium") {
  3951.                                     $medium = $dimensions[$i];
  3952.                                 }*/
  3953.     
  3954.                             }
  3955.     
  3956.                             //strip any url parameters
  3957.                             $path strtok($path"?");
  3958.     
  3959.                             for ($j 0$j count($metricHeaders) && $j count($metrics); $j++) {
  3960.                                 $entry $metricHeaders[$j];
  3961.                                 $values $metrics[$j];
  3962.     
  3963.                                 for ($valueIndex 0$valueIndex count($values->getValues()); $valueIndex++) {
  3964.                                     $value $values->getValues()[$valueIndex];
  3965.                                     //$count = $value;
  3966.                                 }
  3967.                             }
  3968.     
  3969.                             if (!isset($data[$site_config['id']][$path])) {
  3970.                                 $data[$site_config['id']][$path] = (int)$value;
  3971.                             }
  3972.                             /*if (!isset($data[$path]["avgTimeOnPage"])) {
  3973.                                 $data[$path]["avgTimeOnPage"] = $value;
  3974.                             }*/
  3975.                             /*if (!isset($data[$path][$medium])) {
  3976.                                 $data[$path][$medium] = (int)$count;
  3977.                             }
  3978.                             else {
  3979.                                 $data[$path][$medium] += (int)$count;
  3980.                             }*/
  3981.     
  3982.                         }
  3983.                     }
  3984.                     $data[$site_config['id']] = $reports;
  3985.                     //echo "<pre>";var_dump($data);exit;
  3986.                 }
  3987.             //}
  3988.             return $this->defaultRender("test.html.twig", [
  3989.                 "data" => $data
  3990.             ]);
  3991.             //return new JsonResponse(json_encode(print_r($data)), 200, [], true);
  3992.         }
  3993.         /**
  3994.         * @Route("/testtesttestga2")
  3995.         */
  3996.         public function testtesttestga2(
  3997.             Request $request,
  3998.             ContentHelper $contentHelper,
  3999.             CustomerHelper $customerHelper
  4000.         ) {
  4001.             //return false;
  4002.             /**
  4003.              * TODO(developer): Replace this variable with your Google Analytics 4
  4004.              *   property ID before running the sample.
  4005.              */
  4006.             //$property_id = 'YOUR-GA4-PROPERTY-ID';
  4007.             $property_id '320922983';
  4008.             
  4009.             // Using a default constructor instructs the client to use the credentials
  4010.             // specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
  4011.             //$client = new BetaAnalyticsDataClient();
  4012.             $KEY_FILE_LOCATION __DIR__ '/../RCS/RCS Analytics-70262098a89a.json';
  4013.             $client = new BetaAnalyticsDataClient([
  4014.                 'credentials' => $KEY_FILE_LOCATION
  4015.             ]);
  4016.             
  4017.             // Make an API call.
  4018.             $request = (new RunReportRequest())
  4019.                 ->setProperty('properties/' $property_id)
  4020.                 ->setDateRanges([
  4021.                     new DateRange([
  4022.                         'start_date' => '2024-03-31',
  4023.                         'end_date' => 'today',
  4024.                     ]),
  4025.                 ])
  4026.                 ->setDimensions([new Dimension([
  4027.                         'name' => 'city',
  4028.                     ]),
  4029.                 ])
  4030.                 ->setMetrics([new Metric([
  4031.                         'name' => 'activeUsers',
  4032.                     ])
  4033.                 ]);
  4034.             $response $client->runReport($request);
  4035.             
  4036.             // Print results of an API call.
  4037.             
  4038.             $print =  'Report result: ' PHP_EOL;
  4039.             
  4040.             foreach ($response->getRows() as $row) {
  4041.                 $print .= $row->getDimensionValues()[0]->getValue()
  4042.                     . ' ' $row->getMetricValues()[0]->getValue() . PHP_EOL;
  4043.             }
  4044.             
  4045.             
  4046.             
  4047.             $data = [];
  4048.             return $this->defaultRender("test.html.twig", [
  4049.                 //"data" => $data
  4050.                 //"data" => $response
  4051.                 "data" => $print
  4052.             ]);
  4053.             //return new JsonResponse(json_encode(print_r($data)), 200, [], true);
  4054.         }
  4055.         /**
  4056.         * @Route("/testtimeonpage")
  4057.         */
  4058.         public function testtimeonpage(
  4059.             Request $request,
  4060.             ContentHelper $contentHelper,
  4061.             CustomerHelper $customerHelper
  4062.         ) {
  4063.             //return false;
  4064.             $property_id '320922983';
  4065.             $KEY_FILE_LOCATION __DIR__ '/../RCS/RCS Analytics-70262098a89a.json';
  4066.             $client = new BetaAnalyticsDataClient([
  4067.                 'credentials' => $KEY_FILE_LOCATION
  4068.             ]);
  4069.             
  4070.             // Make an API call.
  4071.             $request = (new RunReportRequest())
  4072.                 ->setProperty('properties/' $property_id)
  4073.                 ->setDateRanges([
  4074.                     new DateRange([
  4075.                         'start_date' => '2024-04-01',
  4076.                         'end_date' => '2024-04-30',
  4077.                     ]),
  4078.                 ])
  4079.                 ->setDimensions([new Dimension([
  4080.                         'name' => 'pagePath',
  4081.                     ]),
  4082.                 ])
  4083.                 ->setMetrics([
  4084.                     new Metric(['name' => 'userEngagementDuration']),
  4085.                     new Metric(['name' => 'activeUsers'])
  4086.                 ]);
  4087.             $response $client->runReport($request);
  4088.             
  4089.             // Print results of an API call.
  4090.                 
  4091.             $print =  'Report result: ' PHP_EOL;
  4092.         
  4093.             foreach ($response->getRows() as $row) {
  4094.                 $print .= $row->getDimensionValues()[0]->getValue()
  4095.                     //. ' ' . $row->getMetricValues()[0]->getValue() . PHP_EOL;
  4096.                     ' ' $row->getMetricValues()[0]->getValue()
  4097.                     . ' ' $row->getMetricValues()[1]->getValue() . PHP_EOL;
  4098.             }
  4099.             
  4100.             //$print = \Doctrine\Common\Util\Debug::dump($response, 4);
  4101.             
  4102.             $data = [];
  4103.             return $this->defaultRender("test.html.twig", [
  4104.                 //"data" => $data
  4105.                 //"data" => $response
  4106.                 "data" => $print
  4107.             ]);
  4108.             //return new JsonResponse(json_encode(print_r($data)), 200, [], true);
  4109.         }
  4110.         /**
  4111.         * @Route("/thecoffeeshops")
  4112.         */
  4113.         public function thecoffeeshops(
  4114.             Request $request
  4115.         ) {    
  4116.             return $this->defaultRender("thecoffeeshops.html.twig", [
  4117.                 //"data" => json_decode($resp)
  4118.             ]);
  4119.         }
  4120.     
  4121. }