src/Controller/Master/ContentController.php line 529

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