src/Controller/Master/ContentController.php line 362

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