src/CmsBundle/Controller/PageController.php line 2734

Open in your IDE?
  1. <?php
  2. namespace App\CmsBundle\Controller;
  3. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  4. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  5. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\Routing\Generator\UrlGenerator;
  9. use Symfony\Component\HttpKernel\EventListener\AbstractSessionListener;
  10. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  11. use Symfony\Component\Form\Extension\Core\Type\TextType;
  12. use Symfony\Component\Form\Extension\Core\Type\TextareaType;
  13. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  14. use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
  15. /* Required for file upload */
  16. use Symfony\Component\HttpFoundation\File\UploadedFile;
  17. use Symfony\Component\HttpFoundation\JsonResponse;
  18. use Symfony\Component\Routing\Annotation\Route;
  19. /* Serializer components */
  20. use Symfony\Component\Serializer\Serializer;
  21. use Symfony\Component\Serializer\Encoder\XmlEncoder;
  22. use Symfony\Component\Serializer\Encoder\JsonEncoder;
  23. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  24. use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
  25. use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
  26. use App\CmsBundle\Entity\Page;
  27. use App\CmsBundle\Entity\Tag;
  28. use App\CmsBundle\Entity\PageBlock;
  29. use App\CmsBundle\Entity\PageBlockWrapper;
  30. use App\CmsBundle\Entity\Log;
  31. use App\CmsBundle\Util\Mailer;
  32. use Twig\Environment;
  33. class PageController extends StorageController
  34. {
  35.     /**
  36.      * @Route("/admin/page/save/front", name="admin_page_save_front")
  37.      * @Template()
  38.      */
  39.     public function saveFrontAction(Request $request)
  40.     {
  41.         parent::init($request);
  42.         $status 200;
  43.         $message '';
  44.         $em $this->getDoctrine()->getManager();
  45.         if(!empty($_POST['b'])){
  46.             // Blocks
  47.             foreach($_POST['b'] as $block_id => $fields){
  48.                 $Block $this->getDoctrine()->getRepository('CmsBundle:PageBlock')->find($block_id);
  49.                 if($Block){
  50.                     foreach($fields as $name => $value){
  51.                         if($name == 'content'){
  52.                             $Block->setContent($value);
  53.                         }
  54.                     }
  55.                     $em->persist($Block);
  56.                 }
  57.             }
  58.         }
  59.         $em->flush();
  60.         return new JsonResponse([
  61.             'status' => $status,
  62.             'message' => $message,
  63.         ]);
  64.     }
  65.     /**
  66.      * @Route("/admin/page", name="admin_page")
  67.      * @Template()
  68.      */
  69.     public function indexAction(Request $request)
  70.     {
  71.         parent::init($request);
  72.         $allowCache false; try{ $allowCache $this->containerInterface->getParameter('trinity_cache'); }catch(\Exception $e){}
  73.         if(!empty($_GET['nocache']) || !empty($_GET['resetcache']) || !empty($_GET['timer'])){
  74.             $allowCache false;
  75.         }
  76.         // Check permissions
  77.         if(!$this->getUser()->checkPermissions('ALLOW_PAGE')){
  78.             parent::test_permissions($request$this->getUser());
  79.             throw $this->createNotFoundException('This feature does not exist.');
  80.         }
  81.         $this->breadcrumbs->addRouteItem($this->trans("Pagina's", [], 'cms'), "admin_page");
  82.         $em $this->getDoctrine()->getManager();
  83.         if(!empty($_POST)){
  84.             if(!empty($_POST['bulk-ids'])){
  85.                 $ids explode(','$_POST['bulk-ids']);
  86.                 $action $_POST['bulk-action'];
  87.                 foreach($ids as $id){
  88.                     $Page $this->getDoctrine()->getRepository('CmsBundle:Page')->find($id);
  89.                     if(!empty($Page)){
  90.                         if($action == 'visible-on'){
  91.                             $Page->setVisible(true);
  92.                         }
  93.                         if($action == 'visible-off'){
  94.                             $Page->setVisible(false);
  95.                         }
  96.                         if($action == 'enabled-on'){
  97.                             $Page->setEnabled(true);
  98.                         }
  99.                         if($action == 'enabled-off'){
  100.                             $Page->setEnabled(false);
  101.                         }
  102.                         if ($action == 'pagecache-on') {
  103.                             $Page->setCache(true);
  104.                             $Page->setCacheData(null);
  105.                         }
  106.                         if ($action == 'pagecache-off') {
  107.                             $Page->setCache(false);
  108.                             $Page->setCacheData(null);
  109.                         }
  110.                         if ($action == 'pagecritical-on') {
  111.                             $Page->setCritical(true);
  112.                             $Page->setCricitalCss(null);
  113.                             $this->requestCriticalCss($request$Page);
  114.                         }
  115.                         if ($action == 'pagecritical-off') {
  116.                             $Page->setCritical(false);
  117.                             $Page->setCricitalCss(null);
  118.                         }
  119.                         $em->persist($Page);
  120.                     }
  121.                     $em->flush();
  122.                 }
  123.                 header('Location: /bundles/cms/cache.php?url=' urlencode($this->generateUrl('admin_page')));
  124.                 exit;
  125.             }
  126.             if(!empty($_POST['bulk'])){
  127.                 $bulk trim($_POST['bulk']);
  128.                 // dump($bulk);die();
  129.                 $pageDepth = [];
  130.                 $sort count($this->getDoctrine()->getRepository('CmsBundle:Page')->findAll());
  131.                 foreach(preg_split("/((\r?\n)|(\r\n?))/"$bulk) as $k => $line){
  132.                     $depth strspn($line"\t");
  133.                     $line trim($line);
  134.                     if(substr($line01) == '#') continue;
  135.                     
  136.                     // dump($depth . ': ' . $line);
  137.                     $slug $this->toAscii($line);
  138.                     if($depth 0){
  139.                         $Page $this->getDoctrine()->getRepository('CmsBundle:Page')->findOneBy(['page' => $pageDepth[($depth 1)], 'slug' => $slug]);
  140.                     }else{
  141.                         $Page $this->getDoctrine()->getRepository('CmsBundle:Page')->findOneBy(['page' => null'slug' => $slug]); 
  142.                     }
  143.                     if(empty($Page)){
  144.                         // echo ( '<pre>' . print_r( (str_repeat('- ', $depth)) . 'NEW: ' . $depth . ': ' . $slug, 1 ) . '</pre>' );
  145.                         $Page = new Page();
  146.                         $Page->setLabel($line);
  147.                         $Page->setTitle($line);
  148.                         $Page->setLanguage($this->language);
  149.                         $Page->setSettings($this->Settings);
  150.                         $Page->setSort($sort);
  151.                         $Page->setEnabled(true);
  152.                         $Page->setVisible(false);
  153.                         $Page->setController('CmsBundle:Page:page');
  154.                         $Page->setSlug($slug);
  155.                         $Page->setSlugkey('pages_' $Page->getSlug());
  156.                     }else{
  157.                         // echo ( '<pre>' . print_r( (str_repeat('- ', $depth)) . 'EXISTING: ' . $depth . ': ' . $slug, 1 ) . '</pre>' );
  158.                     }
  159.                     $em->persist($Page);
  160.                     $em->flush();
  161.                     if(!empty($depth)){
  162.                         $Page->setPage($pageDepth[($depth 1)]);
  163.                         $pageDepth[$depth] = $Page;
  164.                         $em->persist($Page);
  165.                         $em->flush();
  166.                     }else{
  167.                         $pageDepth[0] = $Page;
  168.                     }
  169.                     $sort++;
  170.                 }
  171.                 header('Location: /bundles/cms/cache.php?url=' urlencode($this->generateUrl('admin_page')));
  172.                 exit;
  173.             }
  174.             if(!empty($_POST['pagesort'])){
  175.             $pagesort json_decode($_POST['pagesort'], true);
  176.             $sortid 0;
  177.             foreach($pagesort as $index => $pagePos){
  178.                 if(isset($pagePos['id']) && (int)$pagePos['id'] > 0){
  179.                     $Parent $this->getDoctrine()->getRepository('CmsBundle:Page')->findOneById((int)$pagePos['parent_id']);
  180.                     if(is_array($Parent) && empty($Parent)){
  181.                         $Parent null;
  182.                     }
  183.                     $Page $this->getDoctrine()->getRepository('CmsBundle:Page')->findOneById((int)$pagePos['id']);
  184.                     $Page->setPage($Parent)->setSort($sortid);
  185.                     $em->persist($Page);
  186.                     $em->flush();
  187.                     $sortid++;
  188.                 }
  189.             }
  190.             // Send slugs and urls back to template for refreshing new paths
  191.             $slugpaths = array();
  192.             $slugurls = array();
  193.             foreach($pagesort as $index => $pagePos){
  194.                 if(isset($pagePos['id']) && (int)$pagePos['id'] > 0){
  195.                     $Page $this->getDoctrine()->getRepository('CmsBundle:Page')->findOneById((int)$pagePos['id']);
  196.                     $slugpaths[$Page->getId()] = $this->getDoctrine()->getRepository('CmsBundle:Page')->getSlugPathByPage($Page);
  197.                     $slugurls[$Page->getId()] = $this->generateUrl('homepage') . $slugpaths[$Page->getId()];
  198.                 }
  199.             }
  200.             // Clear cache
  201.             // $this->clearcacheAction();
  202.             $Syslog = new Log();
  203.             $Syslog->setUser($this->getUser());
  204.             $Syslog->setUsername($this->getUser()->getUsername());
  205.             $Syslog->setType('page');
  206.             $Syslog->setStatus('info');
  207.             $Syslog->setSettings($this->Settings);
  208.             $Syslog->setAction('sort');
  209.             $Syslog->setMessage('Pagina volgorde is gewijzigd.');
  210.             $em->persist($Syslog);
  211.             $em->flush();
  212.             header('Location: /bundles/cms/cache.php?url=' urlencode($this->generateUrl('admin_page')));
  213.             exit;
  214.         }
  215.         }
  216.         // Find first page
  217.         $ActivePage null;
  218.         $tmp_pages $this->getDoctrine()->getRepository('CmsBundle:Page')->findBy(array('page' => null'language' => $this->language'settings' => $this->Settings), array('sort' => 'ASC'), 1);
  219.         if(!empty($tmp_pages)){
  220.             $ActivePage $tmp_pages[0];
  221.         }
  222.         $pages $this->getPagesByParentid();
  223.         if(!empty($_GET['cloned'])){
  224.             $ClonedPage $this->getDoctrine()->getRepository('CmsBundle:Page')->find((int)$_GET['cloned']);
  225.             $this->addFlash('''<i class="material-icons left">check</i>' $this->trans('Gekopieerd:', [], 'cms') . '&nbsp;<strong>' $ClonedPage->getLabel() . '</strong>.');
  226.             return $this->redirect($this->generateUrl('admin_page'));
  227.         }
  228.         $maxFileSize 10;
  229.         try{
  230.             $maxFileSize = (int)ini_get('upload_max_filesize');
  231.         }catch(\Exception $e){
  232.             // Nothing going on here
  233.         }
  234.         /*return $this->parse('page', array(
  235.             'pages' => $pages
  236.         ));*/
  237.         return $this->attributes(array(
  238.             'pages' => $pages,
  239.             'allowCache' => $allowCache,
  240.             'maxFileSize' => $maxFileSize,
  241.             'ActivePage' => $ActivePage
  242.         ));
  243.     }
  244.     /**
  245.      * @Route("/admin/page/score/{pageid}", name="admin_page_score")
  246.      * @Template()
  247.      */
  248.     public function scoreAction(Request $request$pageid)
  249.     {
  250.         parent::init($request);
  251.         // Check permissions
  252.         if(!$this->getUser()->checkPermissions('ALLOW_PAGE')){
  253.             parent::test_permissions($request$this->getUser());
  254.             throw $this->createNotFoundException('This feature does not exist.');
  255.         }
  256.         $this->breadcrumbs->addRouteItem($this->trans("Pagina's", [], 'cms'), "admin_page");
  257.         $Page $this->getDoctrine()->getRepository('CmsBundle:Page')->find($pageid);
  258.         $parents $Page->getParents();
  259.         if(!empty($parents)){
  260.             foreach(array_reverse($parents) as $Parent){
  261.                 $this->breadcrumbs->addRouteItem($Parent->getLabel(), "admin_page_edit", ['id' => $Parent->getId()]);
  262.             }
  263.         }
  264.         $this->breadcrumbs->addRouteItem($Page->getLabel(), "admin_page_edit", ['id' => $Page->getId()]);
  265.         $this->breadcrumbs->addRouteItem($this->trans('Score', [], 'cms'), "admin_page_score", ['pageid' => $Page->getId()]);
  266.         $scores $Page->getScores();
  267.         return $this->attributes(array(
  268.             'Page' => $Page,
  269.             'scores' => $scores,
  270.             'score' => $scores->first(),
  271.         ));
  272.     }
  273.     /**
  274.      * @Route("/admin/page/media/{pageid}", name="admin_page_media")
  275.      * @Template()
  276.      */
  277.     public function mediaAction(Request $request$pageid)
  278.     {
  279.         parent::init($request);
  280.         $this->breadcrumbs->addRouteItem($this->trans("Pagina's", [], 'cms'), "admin_page");
  281.         // Find first page
  282.         $ActivePage null;
  283.         $tmp_pages $this->getDoctrine()->getRepository('CmsBundle:Page')->findBy(array('page' => null'language' => $this->language), array('sort' => 'ASC'), 1);
  284.         if(!empty($tmp_pages)){
  285.             $ActivePage $tmp_pages[0];
  286.         }
  287.         $ParentPage null;
  288.         $pageSections = array();
  289.         $pageBlockSections = array();
  290.         $block_sections = array();
  291.         $all_block_sections = [];
  292.         $new false;
  293.         $addToParent false;
  294.         // Edit
  295.         $Page $this->getDoctrine()->getRepository('CmsBundle:Page')->find($pageid);
  296.         if($Page->getLanguage() != $this->language){
  297.             // Invalid page! STOP NOW!
  298.             // Try to find alternative page
  299.             $AltPage $this->getDoctrine()->getRepository('CmsBundle:Page')->findOneBy(['slugkey' => $Page->getSlugKey(), 'language' => $this->language]);
  300.             if(!empty($AltPage)){
  301.                 return $this->redirect($this->generateUrl('admin_page_edit', ['id' => $AltPage->getId()]));
  302.             }else{
  303.                 return $this->redirect($this->generateUrl('admin_page'));
  304.             }
  305.         }
  306.         $Page->setUrl($this->generateUrl('homepage') . $this->getDoctrine()->getRepository('CmsBundle:Page')->getSlugPathByPage($Page));
  307.         $parents $Page->getParents();
  308.         if(!empty($parents)){
  309.             foreach(array_reverse($parents) as $Parent){
  310.                 $this->breadcrumbs->addRouteItem($Parent->getLabel(), "admin_page_edit", ['id' => $Parent->getId()]);
  311.             }
  312.         }
  313.         $this->breadcrumbs->addRouteItem($Page->getLabel(), "admin_page_edit", ['id' => $Page->getId()]);
  314.         $this->breadcrumbs->addRouteItem($this->trans('Gekoppelde media', [], 'cms'), "admin_page_media", ['pageid' => $Page->getId()]);
  315.         $usedMedia $this->getDoctrine()->getRepository('CmsBundle:Page')->getUsedMedia($pageid);
  316.         return $this->attributes([
  317.             'usedMedia' => $usedMedia,
  318.             'pageid' => $pageid,
  319.         ]);
  320.     }
  321.     /**
  322.      * @Route("/admin/page/media/download/{pageid}", name="admin_page_media_download")
  323.      * @Template()
  324.      */
  325.     public function mediadownloadAction(Request $request$pageid)
  326.     {
  327.         $Page $this->getDoctrine()->getRepository('CmsBundle:Page')->find($pageid);
  328.         $usedMedia $this->getDoctrine()->getRepository('CmsBundle:Page')->getUsedMedia($pageid);
  329.         $archive_file_name 'media_tmp.zip';
  330.         $zip = new \ZipArchive();
  331.         //create the file and throw the error if unsuccessful
  332.         if ($zip->open($archive_file_name\ZipArchive::CREATE )!==TRUE) {
  333.             exit("cannot open <$archive_file_name>\n");
  334.         }
  335.         foreach($usedMedia as $Media){
  336.             $webdir preg_replace('/^.*?\/public/''public'$Media->getAbsolutePath());
  337.             $zip->addFile($Media->getAbsolutePath(),$webdir);
  338.             $webdir_custom preg_replace('/\/images\//''/images/large/'$webdir);
  339.             $zip->addFile($Media->getAbsolutePath('large'),$webdir_custom);
  340.             $webdir_custom preg_replace('/\/images\//''/images/medium/'$webdir);
  341.             $zip->addFile($Media->getAbsolutePath('medium'),$webdir_custom);
  342.             $webdir_custom preg_replace('/\/images\//''/images/small/'$webdir);
  343.             $zip->addFile($Media->getAbsolutePath('small'),$webdir_custom);
  344.             $webdir_custom preg_replace('/\/images\//''/images/thumb/'$webdir);
  345.             $zip->addFile($Media->getAbsolutePath('thumb'),$webdir_custom);
  346.         }
  347.         $zip->close();
  348.         //then send the headers to force download the zip file
  349.         header("Content-type: application/zip");
  350.         header("Content-Disposition: attachment; filename=$archive_file_name");
  351.         header("Content-length: " filesize($archive_file_name));
  352.         header("Pragma: no-cache");
  353.         header("Expires: 0");
  354.         readfile("$archive_file_name");
  355.         exit;
  356.     }
  357.     /**
  358.      * @Route("/admin/page/selector/{type}", name="admin_page_selector")
  359.      * @Template()
  360.      */
  361.     public function selectorAction(Request $request$type null)
  362.     {
  363.         parent::init($request);
  364.         if($type != null){
  365.             // Find first page
  366.             $ActivePage null;
  367.             $tmp_pages $this->getDoctrine()->getRepository('CmsBundle:Page')->findBy(array('page' => null), array('sort' => 'ASC'), 1);
  368.             if(!empty($tmp_pages)){
  369.                 $ActivePage $tmp_pages[0];
  370.             }
  371.             return $this->attributes(array(
  372.                 'pages' => $this->getPagesByParentid(),
  373.                 'ActivePage' => $ActivePage,
  374.                 'type' => $type
  375.             ));
  376.         }else{
  377.             return $this->attributes(array());
  378.         }
  379.     }
  380.     /**
  381.      * @Route("/admin/page/bundles/{type}", name="admin_page_bundles")
  382.      * @Template()
  383.      */
  384.     public function bundlesAction(Request $request$type null)
  385.     {
  386.         parent::init($request);
  387.         // Check permissions
  388.         if(!$this->getUser()->checkPermissions('ALLOW_PAGE') || !$this->getUser()->checkPermissions('ALLOW_BUNDLES')){
  389.             parent::test_permissions($request$this->getUser());
  390.             throw $this->createNotFoundException('This feature does not exist.');
  391.         }
  392.         $this->breadcrumbs->addRouteItem($this->trans("Gekoppelde extensies", [], 'cms'), "admin_page_bundles");
  393.         // All pages
  394.         $pages $this->getDoctrine()->getRepository('CmsBundle:Page')->findAll();
  395.         $bundleInfo = [];
  396.         foreach($this->modRoutes as $r){
  397.             $bundleInfo[$r['bundleName']] = ['label' => $r['name'], 'icon' => $r['icon'], 'route' => $r['route']];
  398.         }
  399.         // Find blocks containing bundles
  400.         $linked = [];
  401.         $blocks $this->getDoctrine()->getRepository('CmsBundle:PageBlock')->findByData('Trinity%Bundle');
  402.         if(empty($blocks)){
  403.             // Fallback to migrated site
  404.             $blocks $this->getDoctrine()->getRepository('CmsBundle:PageBlock')->findByData('Qinox%Bundle');
  405.         }
  406.         
  407.         foreach($blocks as $Block){
  408.             $bundleData $Block->getBundleData(true);
  409.             $BlockWrapper $Block->getWrapper();
  410.             $Page $BlockWrapper->getPage();
  411.             if($Page){
  412.                 $host 'Onbekend';
  413.                 if(!empty($Page->getSettings())){
  414.                     $host $Page->getSettings()->getHost();
  415.                     if($host == 'null'){
  416.                         $host 'Onbekend';
  417.                     }
  418.                 }
  419.                 $i 1;
  420.                 $block_index 0;
  421.                 foreach($Page->getBlocks() as $Wrapper){
  422.                     if($Wrapper == $BlockWrapper){
  423.                         $block_index $i;
  424.                     }
  425.                     $i++;
  426.                 }
  427.                 if(!isset($linked[$host])){
  428.                     $linked[$host] = [];
  429.                 }
  430.                 if(!isset($linked[$host][$bundleData['bundlename']]) && !empty($bundleInfo[str_replace('Qinox''Trinity'$bundleData['bundlename'])])){
  431.                     $linked[$host][$bundleData['bundlename']] = $bundleInfo[str_replace('Qinox''Trinity'$bundleData['bundlename'])];
  432.                     $linked[$host][$bundleData['bundlename']]['pages'] = [];
  433.                 }
  434.                 $linked[$host][$bundleData['bundlename']]['pages'][] = [
  435.                     'Page' => $Page,
  436.                     'Wrapper' => $BlockWrapper,
  437.                     'Block' => $Block,
  438.                     'bundleData' => $bundleData,
  439.                     'block_index' => $block_index '/' $Page->getBlocks()->count(),
  440.                 ];
  441.             }
  442.         }
  443.         return $this->attributes([
  444.             'linked' => $linked,
  445.         ]);
  446.     }
  447.     /**
  448.      * @Route("/admin/page/list", name="admin_page_list")
  449.      */
  450.     public function listAction(Request $request$returnType null)
  451.     {
  452.         parent::init($request);
  453.         $list $this->getPagesByParentid(nulltrue);
  454.         $return '<ul class="page-list">';
  455.         foreach($list as $id => $pageinfo){
  456.             // die( "<pre>" . print_r( $pageinfo, 1 ) . "</pre>" );
  457.             $return .= '<li style="margin-left:' . ($pageinfo['depth']*20) . 'px;" onclick="pageSelect(' $id ', \'' $pageinfo['slugkey'] . '\', \'' $pageinfo['label'] . '\')">' $pageinfo['label'] . '</li>';
  458.         }
  459.         $return .= '</ul>';
  460.         die($return);
  461.     }
  462.     private function getPagesByParentid($ParentPage null$flat false$depth 0$data = array()){
  463.         if(!$flat$data = array();
  464.         /*if($ParentPage){
  465.             $TranslatedParentPage = $this->getDoctrine()->getRepository('CmsBundle:Page')->findOneBy(['base' => $ParentPage, 'language' => $this->language]);
  466.             if(!empty($TranslatedParentPage)){
  467.                 $ParentPage = $TranslatedParentPage;
  468.             }else{
  469.                 $ParentPage = $ParentPage->getBase();
  470.             }
  471.         }*/
  472.         // $Language = $this->getDoctrine()->getRepository('CmsBundle:Language')->findOneBy([], ['id' => 'asc']);
  473.         $tmp_pages $this->getDoctrine()->getRepository('CmsBundle:Page')->findBy(array('page' => $ParentPage'language' => $this->language'base' => null'settings' => $this->Settings), array('sort' => 'ASC'));
  474.         if(!empty($tmp_pages)){
  475.             foreach($tmp_pages as $Page){
  476.                 /*$TranslatedPage = $this->getDoctrine()->getRepository('CmsBundle:Page')->findOneBy(['base' => $Page, 'language' => $this->language]);
  477.                 $Base = $Page;
  478.                 if(!empty($TranslatedPage)){
  479.                     $Page = $TranslatedPage;
  480.                     $Base = $Page->getBase();
  481.                 }*/
  482.                 if($flat){
  483.                     if($Page->getEnabled()){
  484.                         $data[$Page->getId()] = array(
  485.                             'label'    => $Page->getLabel(),
  486.                             'title'    => $Page->getTitle(),
  487.                             'slug'     => $Page->getSlug(),
  488.                             'slugkey'  => $Page->getSlugKey(),
  489.                             'static'   => $Page->getStatic(),
  490.                             'visible'  => $Page->getVisible(),
  491.                             // 'enabled'  => $Page->getEnabled(),
  492.                             // 'sort'     => $Page->getSort(),
  493.                             'dateadd'  => $Page->getDateAdd(),
  494.                             'dateedit' => $Page->getDateEdit(),
  495.                             'depth'    => $depth,
  496.                         );
  497.                     }
  498.                     $data $this->getPagesByParentid($Page$flat, ($depth+1), $data);
  499.                 }else{
  500.                     $data[] = array(
  501.                         'Page' => $Page->setURL($this->generateUrl('homepage') . $this->getDoctrine()->getRepository('CmsBundle:Page')->getSlugPathByPage($Page)),
  502.                         'children' => $this->getPagesByParentid($Page$flat, ($depth+1), $data)
  503.                     );
  504.                 }
  505.             }
  506.         }
  507.         return $data;
  508.     }
  509.     /**
  510.      * @Route("/admin/page/download/{id}", name="admin_page_download")
  511.      * @Template()
  512.      */
  513.     public function downloadAction(Request $request$id)
  514.     {
  515.         $exportId time() . '_';
  516.         $encoders = array(new XmlEncoder(), new JsonEncoder());
  517.         $defaultContext = [
  518.             AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER => function ($object$format$context) {
  519.                 return $object->getId();
  520.             },
  521.             AbstractNormalizer::IGNORED_ATTRIBUTES => ['page''language''versions''parents''dateAdd''dateEdit''children''metatags''settings''scores']
  522.         ];
  523.         $normalizer = new ObjectNormalizer(nullnullnullnullnullnull$defaultContext);
  524.         $normalizers = array($normalizer);
  525.         $serializer = new Serializer($normalizers$encoders);
  526.         $Page $this->getDoctrine()->getRepository('CmsBundle:Page')->find($id);
  527.         $jsonContent $serializer->serialize($Page'json');
  528.         // Gather media
  529.         $mediaList = [];
  530.         foreach($Page->getBlocks() as $Wrapper){
  531.             foreach($Wrapper->getBlocks() as $Block){
  532.                 if(!empty($Block->getMedia())){
  533.                     $mediaList[$Block->getMedia()->getId()] = $Block->getMedia();
  534.                 }
  535.                 if($Block->getAltMedia()->count()){
  536.                     foreach($Block->getAltMedia() as $m){
  537.                         $Media $m->getMedia();
  538.                         $mediaList[$Media->getId()] = $Media;
  539.                     }
  540.                 }
  541.             }
  542.         }
  543.         $files = [$exportId 'page.json'];
  544.         file_put_contents('/tmp/' $exportId 'page.json'$jsonContent);
  545.         if(!empty($mediaList)){
  546.             $defaultContext = [
  547.                 AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER => function ($object$format$context) {
  548.                     return $object->getId();
  549.                 },
  550.                 AbstractNormalizer::IGNORED_ATTRIBUTES => ['dateAdd''dateEdit''children''block''tags''parent']
  551.             ];
  552.             $normalizer = new ObjectNormalizer(nullnullnullnullnullnull$defaultContext);
  553.             $normalizers = array($normalizer);
  554.             $serializer = new Serializer($normalizers$encoders);
  555.             $mediaJsonData = ($serializer->serialize($mediaList'json'));
  556.             file_put_contents('/tmp/' $exportId 'media.json'$mediaJsonData);
  557.             $files[] = $exportId 'media.json';
  558.             $mediaPath '/tmp/' $exportId 'media/';
  559.             if(!file_exists($mediaPath)) mkdir($mediaPath);
  560.             foreach($mediaList as $Media){
  561.                 $dir str_replace('src/CmsBundle/Controller''public/uploads/' $Media->getType() . '/'__DIR__);
  562.                 $files[] = [$dir.$Media->getPath(),'media/' $Media->getLabel()];
  563.             }
  564.         }
  565.         $zip = new \ZipArchive();
  566.         $filepath '/tmp/' $exportId $Page->getSlug() . '.zip';
  567.         $filename $exportId $Page->getSlug() . '.zip';
  568.         if ($zip->open($filepath\ZipArchive::CREATE)!==TRUE) {
  569.             exit("cannot open <$filepath>\n");
  570.         }
  571.         foreach($files as $f){
  572.             if(is_array($f)){
  573.                 $zip->addFile($f[0], $f[1]);
  574.             }else{
  575.                 $zip->addFile('/tmp/' $f$f);
  576.             }
  577.         }
  578.         $zip->close();
  579.         header("Content-type: application/zip");
  580.         header("Content-Disposition: attachment; filename=$filename");
  581.         header("Content-length: " filesize($filepath));
  582.         header("Pragma: no-cache");
  583.         header("Expires: 0");
  584.         readfile("$filepath");
  585.         /*header('Content-disposition: attachment; filename=tpd_' . $Page->getSlug() . '.json');
  586.         header('Content-type: application/json');
  587.         echo $jsonContent;*/
  588.         exit;
  589.     }
  590.     /**
  591.      * @Route("/admin/page/import", name="admin_page_import")
  592.      * @Template()
  593.      */
  594.     public function importAction(Request $request)
  595.     {
  596.         parent::init($request);
  597.         if(!empty($_FILES['file']) && $_FILES['file']['error'] == 0){
  598.             $f $_FILES['file'];
  599.             if($f['type'] == 'application/zip' || $f['type'] == 'application/x-zip-compressed'){
  600.                 $importId time();
  601.                 $filePath '/tmp/' $importId '/';
  602.                 // Extract zip
  603.                 $zip = new \ZipArchive;
  604.                 if ($zip->open($f['tmp_name']) === TRUE) {
  605.                     $zip->extractTo($filePath);
  606.                     $zip->close();
  607.                     $files scandir($filePath);
  608.                     // Validate files
  609.                     $pageFile  null;
  610.                     $mediaFile null;
  611.                     $mediaDir  null;
  612.                     $found 0;
  613.                     foreach($files as $f){
  614.                         if(preg_match('/_media\.json/'$f)){
  615.                             $found++;
  616.                             $mediaFile $filePath $f;
  617.                         }else if(preg_match('/_page\.json/'$f)){
  618.                             $found++;
  619.                             $pageFile $filePath $f;
  620.                         }else if($f == 'media'){
  621.                             $found++;
  622.                             $mediaDir $filePath 'media/';
  623.                         }
  624.                     }
  625.                     if($pageFile && (empty($mediaFile) || ($mediaFile && $mediaDir))){
  626.                         $em $this->getDoctrine()->getManager();
  627.                         $convert = [];
  628.                         if($mediaFile){
  629.                             $data = (string)file_get_contents($mediaFile);
  630.                             $json json_decode($datatrue);
  631.                             foreach($json as $old_id => $data){
  632.                                 $dirPath array_reverse(explode(' / '$data['folderPath']));
  633.                                 foreach($dirPath as $k => $v){ if(empty($v)){ unset($dirPath[$k]); } }
  634.                                 $dirPath implode('/'$dirPath) . '_' $importId;
  635.                                 $mediaParent $this->getDoctrine()->getRepository('CmsBundle:Mediadir')->findPathByName($em$dirPath$this->language);
  636.                                 $filename $data['label'];
  637.                                 $realFile $mediaDir.$filename;
  638.                                 $filesize filesize($realFile);
  639.                                 $UploadedFile = new UploadedFile($realFile$filename$data['type'], 0true );
  640.                                 $Media = new \App\CmsBundle\Entity\Media();
  641.                                 $Media->setParent($mediaParent);
  642.                                 $Media->setLabel($filename);
  643.                                 $Media->setDateAdd();
  644.                                 $Media->setFile($UploadedFile); // Link UploadedFile to the media entity
  645.                                 $Media->preUpload(); // Prepare file and path
  646.                                 $Media->upload(); // Upload actual file
  647.                                 $Media->setSize($filesize);
  648.                                 $em->persist($Media);
  649.                                 $convert[$old_id] = $Media;
  650.                             }
  651.                         }
  652.                         /*dump($mediaFile);
  653.                         dump($pageFile);
  654.                         dump($mediaDir);
  655.                         die();*/
  656.                         $data = (string)file_get_contents($pageFile);
  657.                         $json json_decode($datatrue);
  658.                         $encoders = array(new XmlEncoder(), new JsonEncoder());
  659.                         $defaultContext = [
  660.                             AbstractNormalizer::IGNORED_ATTRIBUTES => ['media''pages''blocks''wrapper''page''tags''content''image''language''metatags''versions''scores''altMedia''settings']
  661.                         ];
  662.                         $normalizer = new ObjectNormalizer(nullnullnull, new ReflectionExtractor(), nullnull$defaultContext); //
  663.                         $normalizers = array($normalizer);
  664.                         $serializer = new Serializer($normalizers$encoders);
  665.                         // Initial page
  666.                         $repairJson json_decode($datatrue);
  667.                         $repairJson['cache'] = true;
  668.                         $data json_encode($repairJson);
  669.                         $Page $serializer->deserialize($dataPage::class, 'json');
  670.                         // Check if page with same slug key already exists
  671.                         $TestPage $this->getDoctrine()->getRepository('CmsBundle:Page')->findOneBy(['slugkey' => $Page->getSlugKey(), 'settings' => $this->Settings]);
  672.                         if($TestPage){
  673.                             // Page with same slugkey already exists, add ' - Kopie' suffix
  674.                             $Page->setLabel($json['label'] . ' - Kopie');
  675.                             $Page->setSlug($this->toAscii($Page->getLabel())); // Make slug lowercase and remove chars
  676.                             $Page->setSlugkey('pages_' $Page->getSlug());
  677.                         }else{
  678.                             $Page->setLabel($json['label']);
  679.                             $Page->setSlug($json['slug']);
  680.                             $Page->setSlugkey('pages_' $json['slug']);
  681.                         }
  682.                         $Page->setLanguage($this->language);
  683.                         $Page->setEnabled(true);
  684.                         $Page->setVisible(false);
  685.                         
  686.                         $Page->setSettings($this->Settings);
  687.                         // FIX MISSING LAYOUT
  688.                         $layout $Page->getLayout();
  689.                         $layoutPath $this->containerInterface->get('kernel')->getProjectDir() . '/templates/layouts/';
  690.                         if(!empty($layout)){
  691.                             $layoutFile $layoutPath $layout '.html.twig';
  692.                             if(!file_exists($layoutFile)){
  693.                                 $Page->setLayout('');
  694.                             }
  695.                         }
  696.                         $em->persist($Page);
  697.                         foreach($json['blocks'] as $block){
  698.                             $PageBlockWrapper $serializer->deserialize(json_encode($block), PageBlockWrapper::class, 'json');
  699.                             $PageBlockWrapper->setPage($Page);
  700.                             $em->persist($PageBlockWrapper);
  701.                             foreach($block['blocks'] as $child_block){
  702.                                 // Repairs
  703.                                 if(empty($child_block['bundle'])){ $child_block['bundle'] = ''; }
  704.                                 if(empty($child_block['bundleLabel'])){ $child_block['bundleLabel'] = ''; }
  705.                                 if(empty($child_block['bundleData'])){ $child_block['bundleData'] = ''; }
  706.                                 if(empty($child_block['contained'])){ $child_block['contained'] = ''; }
  707.                                 $PageBlock $serializer->deserialize(json_encode($child_block), PageBlock::class, 'json');
  708.                                 $PageBlock->setWrapper($PageBlockWrapper);
  709.                                 $content = [];
  710.                                 // Gather media
  711.                                 if(!empty($child_block['media'])){
  712.                                     $m $convert[$child_block['media']['id']];
  713.                                     $PageBlock->setMedia($m);
  714.                                     $content[] = $m->getId() . ',/' $m->getWebPath() . ',' $m->getLabel();
  715.                                 }
  716.                                 if(!empty($child_block['altMedia'])){
  717.                                     $PageBlock->clearAltMedia();
  718.                                     $ac = new \Doctrine\Common\Collections\ArrayCollection();
  719.                                     foreach($child_block['altMedia'] as $m){
  720.                                         $m $convert[$m['media']['id']];
  721.                                         $content[] = $m->getId() . ',/' $m->getWebPath() . ',' $m->getLabel();
  722.                                         $BlockMedia = new \App\CmsBundle\Entity\PageBlockMedia();
  723.                                         $BlockMedia->setMedia($m);
  724.                                         $BlockMedia->addPageBlock($PageBlock);
  725.                                         $em->persist($BlockMedia);
  726.                                         $PageBlock->addAltMedia($BlockMedia);
  727.                                     }
  728.                                 }
  729.                                 if(!empty($content)){
  730.                                     $PageBlock->setContent(implode(';'$content));
  731.                                 }else{
  732.                                     if(!empty($child_block['content'])){
  733.                                         $PageBlock->setContent($child_block['content']);
  734.                                     }
  735.                                 }
  736.                                 $em->persist($PageBlock);
  737.                                 $PageBlockWrapper->addBlock($PageBlock);
  738.                             }
  739.                             $Page->addBlock($PageBlockWrapper);
  740.                         }
  741.                         // if(!empty($json['pages'])){
  742.                         //     foreach($json['pages'] as $json){
  743.                         //         $data = json_encode($json);
  744.                         //         // Initial page
  745.                         //         $ChildPage = $serializer->deserialize($data, Page::class, 'json');
  746.                         //         $ChildPage->setLabel($json['label']);
  747.                         //         $ChildPage->setLanguage($this->language);
  748.                         //         $ChildPage->setPage($Page);
  749.                         //         $em->persist($ChildPage);
  750.                         //         foreach($json['blocks'] as $block){
  751.                         //             $ChildPageBlockWrapper = $serializer->deserialize(json_encode($block), PageBlockWrapper::class, 'json');
  752.                         //             $ChildPageBlockWrapper->setPage($ChildPage);
  753.                         //             $em->persist($ChildPageBlockWrapper);
  754.                         //             foreach($block['blocks'] as $child_block){
  755.                         //                 $ChildPageBlock = $serializer->deserialize(json_encode($child_block), PageBlock::class, 'json');
  756.                         //                 $ChildPageBlock->setWrapper($ChildPageBlockWrapper);
  757.                         //                 $em->persist($ChildPageBlock);
  758.                         //             }
  759.                         //         }
  760.                         //         if(!empty($json['pages'])){
  761.                         //             foreach($json['pages'] as $json){
  762.                         //                 $data = json_encode($json);
  763.                         //                 // Initial page
  764.                         //                 $SubChildPage = $serializer->deserialize($data, Page::class, 'json');
  765.                         //                 $SubChildPage->setLabel($json['label']);
  766.                         //                 $SubChildPage->setLanguage($this->language);
  767.                         //                 $SubChildPage->setPage($ChildPage);
  768.                         //                 $em->persist($SubChildPage);
  769.                         //                 foreach($json['blocks'] as $block){
  770.                         //                     $SubChildPageBlockWrapper = $serializer->deserialize(json_encode($block), PageBlockWrapper::class, 'json');
  771.                         //                     $SubChildPageBlockWrapper->setPage($SubChildPage);
  772.                         //                     $em->persist($SubChildPageBlockWrapper);
  773.                         //                     foreach($block['blocks'] as $child_block){
  774.                         //                         $SubChildPageBlock = $serializer->deserialize(json_encode($child_block), PageBlock::class, 'json');
  775.                         //                         $SubChildPageBlock->setWrapper($SubChildPageBlockWrapper);
  776.                         //                         $em->persist($SubChildPageBlock);
  777.                         //                     }
  778.                         //                 }
  779.                         //             }
  780.                         //         }
  781.                         //     }
  782.                         // }
  783.                         $em->flush();
  784.                         $this->addFlash('''<i class="material-icons left">check</i>' $this->trans('Import is voltooid.', [], 'cms'));
  785.                         if($request->isXmlHttpRequest()) {
  786.                             return new JsonResponse(['success' => true'message' => 'Import was successful']);
  787.                         }else{
  788.                             header('Location: /bundles/cms/cache.php?url=' urlencode($this->generateUrl('admin_page')));
  789.                             exit;
  790.                         }
  791.                     }else{
  792.                         $this->addFlash('''<i class="material-icons left">clear</i>' $this->trans('De inhoud van het ZIP-bestand is ongeldig.', [], 'cms'));
  793.                         if($request->isXmlHttpRequest()) {
  794.                             return new JsonResponse(['success' => false'message' => 'The ZIP contents are not valid']);
  795.                         }else{
  796.                             return $this->redirect($this->generateUrl('admin_page'));
  797.                         }
  798.                     }
  799.                 }else{
  800.                     $this->addFlash('''<i class="material-icons left">clear</i>'$this->trans('Het uitpakken is mislukt.', [], 'cms'));
  801.                     if($request->isXmlHttpRequest()) {
  802.                         return new JsonResponse(['success' => false'message' => 'Unzip failed''file' => $f['tmp_name'], 'path' => $filePath]);
  803.                     }else{
  804.                         return $this->redirect($this->generateUrl('admin_page'));
  805.                     }
  806.                 }
  807.             }else{
  808.                 $this->addFlash('''<i class="material-icons left">clear</i>' $this->trans('Het bestand bevat geen geldig bestandstype.', [], 'cms'));
  809.                 if($request->isXmlHttpRequest()) {
  810.                     return new JsonResponse(['success' => false'message' => 'Invalid filetype: ' $f['type']]);
  811.                 }else{
  812.                     return $this->redirect($this->generateUrl('admin_page'));
  813.                 }
  814.             }
  815.         }
  816.         return $this->attributes([]);
  817.     }
  818.     /**
  819.      * @Route("/admin/page/inactive", name="admin_page_inactive")
  820.      * @Template()
  821.      */
  822.     public function inactiveAction(Request $request)
  823.     {
  824.         parent::init($request);
  825.         // Check permissions
  826.         if(!$this->getUser()->checkPermissions('ALLOW_PAGE')){
  827.             parent::test_permissions($request$this->getUser());
  828.             throw $this->createNotFoundException('This feature does not exist.');
  829.         }
  830.         $this->breadcrumbs->addRouteItem($this->trans("Pagina's", [], 'cms'), "admin_page");
  831.         $this->breadcrumbs->addRouteItem($this->trans("Inactief", [], 'cms'), "admin_page_inactive");
  832.         return $this->attributes(array(
  833.         ));
  834.     }
  835.     /**
  836.      * @Route("/admin/page/modified", name="admin_page_modified")
  837.      * @Template()
  838.      */
  839.     public function modifiedAction(Request $request)
  840.     {
  841.         parent::init($request);
  842.         // Check permissions
  843.         if(!$this->getUser()->checkPermissions('ALLOW_PAGE')){
  844.             parent::test_permissions($request$this->getUser());
  845.             throw $this->createNotFoundException('This feature does not exist.');
  846.         }
  847.         $this->breadcrumbs->addRouteItem($this->trans("Pagina's", [], 'cms'), "admin_page");
  848.         $this->breadcrumbs->addRouteItem($this->trans("Recentelijk gewijzigd", [], 'cms'), "admin_page_modified");
  849.         return $this->attributes(array(
  850.         ));
  851.     }
  852.     /**
  853.      * @Route("/admin/page/composer/uploadhandler/{pageid}", name="admin_page_composer_uploadhandler")
  854.      */
  855.     public function composerUploadActionRequest $request$pageid null){
  856.         $f $_FILES['media'];
  857.         // Media upload
  858.         // $mediaParent = $this->getDoctrine()->getRepository('CmsBundle:Mediadir')->findPathByName($em, $dirPath);
  859.         $filesize filesize($f['tmp_name']);
  860.         $UploadedFile = new UploadedFile($f['tmp_name'], $f['name'], $f['type'], 0true );
  861.         $Media = new \App\CmsBundle\Entity\Media();
  862.         // $Media->setParent($mediaParent);
  863.         $Media->setLabel($f['name']);
  864.         $Media->setDateAdd();
  865.         $Media->setFile($UploadedFile); // Link UploadedFile to the media entity
  866.         $Media->preUpload(); // Prepare file and path
  867.         $Media->upload(); // Upload actual file
  868.         $Media->setSize($filesize);
  869.         $em $this->getDoctrine()->getManager();
  870.         $em->persist($Media);
  871.         $em->flush();
  872.         return new JsonResponse([
  873.             'id'       => $Media->getId(),
  874.             'filename' => $f['name'],
  875.             'path'     => '/' $Media->getWebPath('small'),
  876.             'width'     => $Media->getWidth(),
  877.         ]);
  878.     }
  879.     private function ImageRectangleWithRoundedCorners(&$im$x1$y1$x2$y2$radius$color) {
  880.         if(is_array($color)){
  881.             $color imagecolorallocate($im$color[0], $color[1], $color[2]);
  882.         }
  883.         // draw rectangle without corners
  884.         imagefilledrectangle($im$x1+$radius$y1$x2-$radius$y2$color);
  885.         imagefilledrectangle($im$x1$y1+$radius$x2$y2-$radius$color);
  886.         // draw circled corners
  887.         imagefilledellipse($im$x1+$radius$y1+$radius$radius*2$radius*2$color);
  888.         imagefilledellipse($im$x2-$radius$y1+$radius$radius*2$radius*2$color);
  889.         imagefilledellipse($im$x1+$radius$y2-$radius$radius*2$radius*2$color);
  890.         imagefilledellipse($im$x2-$radius$y2-$radius$radius*2$radius*2$color);
  891.     }
  892.     /**
  893.      * @Route("/admin/page/icon/{id}/{icon_size}", name="admin_page_icon")
  894.      */
  895.     public function iconActionRequest $request$id$icon_size 100$method '')
  896.     {
  897.         $bgcolor = [255255255]; // RGB
  898.         $blockcolors = [
  899.             [23155222],
  900.             [23155222],
  901.             [23155222],
  902.             [23155222],
  903.             [23155222],
  904.         ]; // RGB
  905.         $margin 6;
  906.         if($icon_size <= 50){
  907.             $margin 3;
  908.         }elseif($icon_size <= 100){
  909.             $margin 5;
  910.         }elseif($icon_size >= 400){
  911.             $margin 15;
  912.         }elseif($icon_size >= 500){
  913.             $margin 20;
  914.         }
  915.         $y_offset $margin;
  916.         $im imagecreatetruecolor($icon_size$icon_size);
  917.         imagealphablending($im false);
  918.         imagesavealpha($im true);
  919.         imagecolortransparent ($im0);
  920.         $bg imagecolorallocatealpha($im2552552550);
  921.         imagefill($im00$bg);
  922.         
  923.         $text_color imagecolorallocate($im255255255);
  924.         $radius ceil(($icon_size 100) * 7); // 5% of icon size
  925.         foreach($blockcolors as $n => $blockcolor){
  926.             $blockcolors[$n] = imagecolorallocate($im$blockcolor[0], $blockcolor[1], $blockcolor[2]);
  927.         }
  928.         // $background_color = imagecolorallocate($im, $bgcolor[0], $bgcolor[1], $bgcolor[2]);
  929.         if($icon_size <= 100){
  930.             imagefilledrectangle($im00$icon_size$icon_sizeimagecolorallocate($im$bgcolor[0], $bgcolor[1], $bgcolor[2]));
  931.         }else{
  932.             $this->ImageRectangleWithRoundedCorners($im00$icon_size$icon_size$radius$bgcolor);
  933.         }
  934.         $n 0;
  935.         if(!empty($id) && is_numeric($id)){
  936.             $Page $this->getDoctrine()->getRepository('CmsBundle:Page')->find($id);
  937.             if($Page->getBlocks()->count() > 0){
  938.         
  939.                 $block_amount_vertical $Page->getBlocks()->count();
  940.                 if($block_amount_vertical 5){
  941.                     $block_amount_vertical 5;
  942.                 }
  943.                 $block_height = ((($icon_size 100) * (100 $block_amount_vertical))) - $margin// 20% of icon size
  944.                 $block_height -= ($margin $block_amount_vertical);
  945.                 // Has at least one block
  946.                 foreach($Page->getBlocks() as $BlockWrapper){
  947.                     $block_height_curr $block_height;
  948.                     $grid_size $BlockWrapper->getGridSize();
  949.                     if($grid_size === 0){
  950.                         $grid_size 1;
  951.                     }
  952.                     // imagefilledrectangle($im, $margin, $y_offset, ($icon_size - $margin), $y_offset + $block_height, $blockcolors[$n]);
  953.                     $blockRadius = (($radius 100) * 75);
  954.                     if($blockRadius > ($block_height 2.5)){
  955.                         $blockRadius = ($block_height 2.5);
  956.                     }
  957.                     $label $BlockWrapper->getLabel();
  958.                     
  959.                     if($BlockWrapper->getBlocks()->count() > $grid_size){
  960.                         $grid_size $BlockWrapper->getBlocks()->count();
  961.                     }
  962.                     $margin_x $margin;
  963.                     foreach($BlockWrapper->getBlocks() as $Block){
  964.                         // dump($Block);
  965.                         $bw = ($icon_size - ($margin 1));
  966.                         $bw_for_lbl $bw;
  967.                         $bw = ($bw $grid_size);
  968.                         $bw = ($bw $margin);
  969.                         if(preg_match('/hero/'$BlockWrapper->getTemplateKey())){
  970.                             // Dual height
  971.                             $block_height_curr = ($block_height_curr 2) + $margin;
  972.                             $label 'Hero';
  973.                         }
  974.                         $data $Block->getData();
  975.                         // if($icon_size <= 100){
  976.                             imagefilledrectangle($im$margin_x$y_offset$margin_x $bw, ($y_offset $block_height_curr), $blockcolors[$n]);
  977.                         // }else{
  978.                         //     $this->ImageRectangleWithRoundedCorners($im, $margin_x, $y_offset, $margin_x + $bw, ($y_offset + $block_height_curr), $blockRadius, $blockcolors[$n]);
  979.                         // }
  980.                         $icon_scale 1.5;
  981.                         if($icon_size >= 400){
  982.                             $icon_scale 2.5;
  983.                         }else if($icon_size >= 200){
  984.                             $icon_scale 2;
  985.                         }
  986.                         if(!empty($label)){
  987.                             $font_size 5;
  988.                             if($icon_size 110){
  989.                                 $label '';
  990.                             }elseif($icon_size 120){
  991.                                 $font_size 2;
  992.                             }elseif($icon_size 150){
  993.                                 $font_size 3;
  994.                             }elseif($icon_size 200){
  995.                                 $font_size 5;
  996.                             }
  997.                             $tw = (strlen($label) * imagefontwidth($font_size));
  998.                             $th imagefontheight($font_size);
  999.                             imagestring($im$font_size$margin + (($bw_for_lbl 2) - ($tw 2)), ($y_offset + (($block_height_curr 2) - ($th 2))),  $label$text_color);
  1000.                         }else{
  1001.                             if($Block->getContentType() == 'bundle'){
  1002.                                 $icon_bundle str_replace('/Controller''/Storage'__DIR__) . '/block_bundle.png';
  1003.                                 $im_ico_bundle imagecreatefrompng($icon_bundle);
  1004.                                 $ico_size = ($block_height_curr $icon_scale);
  1005.                                 imagecopyresized($im$im_ico_bundle, (($margin_x + ($bw 2)) - ($ico_size 2)), $y_offset + (($block_height_curr 2) - ($ico_size 2)), 00$ico_size$ico_size150150);    
  1006.                             }else if($Block->getContentType() == 'source'){
  1007.                                 $icon_source str_replace('/Controller''/Storage'__DIR__) . '/block_source.png';
  1008.                                 $im_ico_source imagecreatefrompng($icon_source);
  1009.                                 $ico_size = ($block_height_curr $icon_scale);
  1010.                                 imagecopyresized($im$im_ico_source, (($margin_x + ($bw 2)) - ($ico_size 2)), $y_offset + (($block_height_curr 2) - ($ico_size 2)), 00$ico_size$ico_size150150);    
  1011.                             }else if(!empty($data['type']) && $data['type'] == 'video'){
  1012.                                 $icon_video str_replace('/Controller''/Storage'__DIR__) . '/block_video.png';
  1013.                                 $im_ico_video imagecreatefrompng($icon_video);
  1014.                                 $ico_size = ($block_height_curr $icon_scale);
  1015.                                 imagecopyresized($im$im_ico_video, (($margin_x + ($bw 2)) - ($ico_size 2)), $y_offset + (($block_height_curr 2) - ($ico_size 2)), 00$ico_size$ico_size150150);    
  1016.                             }else if($Block->getMedia()){
  1017.                                 $icon_img str_replace('/Controller''/Storage'__DIR__) . '/block_img.png';
  1018.                                 $im_ico_img imagecreatefrompng($icon_img);
  1019.                                 $ico_size = ($block_height_curr $icon_scale);
  1020.                                 imagecopyresized($im$im_ico_img, (($margin_x + ($bw 2)) - ($ico_size 2)), $y_offset + (($block_height_curr 2) - ($ico_size 2)), 00$ico_size$ico_size150150);
  1021.                             }else if($Block->getContent()){
  1022.                                 $icon_text str_replace('/Controller''/Storage'__DIR__) . '/block_text.png';
  1023.                                 $im_ico_text imagecreatefrompng($icon_text);
  1024.                                 $ico_size = ($block_height_curr $icon_scale);
  1025.                                 imagecopyresized($im$im_ico_text, (($margin_x + ($bw 2)) - ($ico_size 2)), $y_offset + (($block_height_curr 2) - ($ico_size 2)), 00$ico_size$ico_size150150);    
  1026.                             }
  1027.                         }
  1028.                         $margin_x += ($bw $margin);
  1029.                     }
  1030.                     $y_offset += ($block_height_curr $margin);
  1031.                     $n++;
  1032.                     if($n > ($block_amount_vertical 1)){
  1033.                         break;
  1034.                     }
  1035.                 }
  1036.                     // die();
  1037.             }
  1038.         }
  1039.         if($method == 'base64'){
  1040.             ob_start(); // Let's start output buffering.
  1041.             imagepng($im); //This will normally output the image, but because of ob_start(), it won't.
  1042.             $contents ob_get_contents(); //Instead, output above is saved to $contents
  1043.             ob_end_clean(); //End the output buffer.
  1044.             return 'data:image/png;base64,' base64_encode($contents);
  1045.         }
  1046.         header("Content-Type: image/png");
  1047.         imagepng($im);
  1048.         imagedestroy($im);
  1049.         exit;
  1050.     }
  1051.     /**
  1052.      * @Route("/admin/page/savetemplate/{id}", name="admin_page_savetemplate")
  1053.      * @Template()
  1054.      */
  1055.     public function savetemplateActionRequest $request$id null)
  1056.     {
  1057.         parent::init($request);
  1058.         // Check permissions
  1059.         if(!$this->getUser()->checkPermissions('ALLOW_PAGE')){
  1060.             parent::test_permissions($request$this->getUser());
  1061.             throw $this->createNotFoundException('This feature does not exist.');
  1062.         }
  1063.         $this->breadcrumbs->addRouteItem($this->trans("Opslaan als sjabloon", [], 'cms'), "admin_page");
  1064.         $Page $this->getDoctrine()->getRepository('CmsBundle:Page')->find($id);
  1065.         $json_file str_replace('/src/CmsBundle/Controller''/'__DIR__) . 'page_teplates.json';
  1066.         if(!empty($_POST)){
  1067.             if(!empty($_POST['label'])){
  1068.                 $label $_POST['label'];
  1069.                 $description $_POST['description'];
  1070.                 $templates_json = [];
  1071.                 if(file_exists($json_file)){
  1072.                     $templates_json json_decode(file_get_contents($json_file), true);
  1073.                 }
  1074.                 $icon_small $this->iconAction($request$id150'base64');
  1075.                 $icon_big $this->iconAction($request$id350'base64');
  1076.                 $layout = [];
  1077.                 foreach($Page->getBlocks() as $BlockWrapper){
  1078.                     foreach($BlockWrapper->getBlocks() as $Block){
  1079.                         dump($Block);die();
  1080.                     }
  1081.                 }
  1082.                 $templates_json[$label] = [
  1083.                     'label'       => $label,
  1084.                     'description' => $description,
  1085.                     'icon_small'  => $icon_small,
  1086.                     'icon_big'    => $icon_big,
  1087.                     'layout'      => $layout,
  1088.                 ];
  1089.                 file_put_contents($json_filejson_encode($templates_json));
  1090.                 die('..');
  1091.             }
  1092.         }
  1093.         return $this->attributes([
  1094.             'Page' => $Page,
  1095.         ]);
  1096.     }
  1097.     /**
  1098.      * @Route("/admin/page/edit/{id}", name="admin_page_edit")
  1099.      * @Template()
  1100.      */
  1101.     public function editActionRequest $request$id null)
  1102.     {
  1103.         parent::init($request);
  1104.         // Check permissions
  1105.         if(!$this->getUser()->checkPermissions('ALLOW_PAGE')){
  1106.             parent::test_permissions($request$this->getUser());
  1107.             throw $this->createNotFoundException('This feature does not exist.');
  1108.         }
  1109.         $this->breadcrumbs->addRouteItem($this->trans("Pagina's", [], 'cms'), "admin_page");
  1110.         $usedBlockDir $this->containerInterface->get('kernel')->getProjectDir() . '/var/cache';
  1111.          if(!file_exists($usedBlockDir)){
  1112.             mkdir($usedBlockDir);
  1113.         }
  1114.         $usedBlocks = ['framework_empty'];
  1115.         $usedBlockJSON $usedBlockDir '/usedBlocks_' $this->Settings->getID() . '.json';
  1116.         if (file_exists($usedBlockJSON)) {
  1117.             $usedBlocks file_get_contents($usedBlockJSON);
  1118.             $usedBlocks json_decode($usedBlocksJSON_FORCE_OBJECT);
  1119.         }
  1120.         // Find first page
  1121.         $ActivePage null;
  1122.         $tmp_pages $this->getDoctrine()->getRepository('CmsBundle:Page')->findBy(array('page' => null'language' => $this->language), array('sort' => 'ASC'), 1);
  1123.         if(!empty($tmp_pages)){
  1124.             $ActivePage $tmp_pages[0];
  1125.         }
  1126.         $ParentPage null;
  1127.         $pageSections = array();
  1128.         $pageBlockSections = array();
  1129.         $block_sections = array();
  1130.         $all_block_sections = [];
  1131.         $new false;
  1132.         $addToParent false;
  1133.         if( (int)$id ){
  1134.             // Edit
  1135.             $Page $this->getDoctrine()->getRepository('CmsBundle:Page')->find($id);
  1136.             // FIX MISSING LAYOUT
  1137.             $layout $Page->getLayout();
  1138.             $layoutPath $this->containerInterface->get('kernel')->getProjectDir() . '/templates/layouts/';
  1139.             if(empty($layout)) $layout 'default';
  1140.             $layoutFile $layoutPath $layout '.html.twig';
  1141.             if(strpos($layout':') !== false){
  1142.                 $layout_arr explode(':'$layout);
  1143.                 if(in_array($layout_arr[0], $this->installed)){
  1144.                     $bundleDir $this->containerInterface->get('kernel')->getProjectDir() . '/src/Trinity/' $layout_arr[0] . '/Resources/views/Cms/Layouts/';
  1145.                     $layoutFile $bundleDir $layout_arr[1] . '.html.twig';
  1146.                 }
  1147.             }
  1148.             if(!file_exists($layoutFile)){
  1149.                 $Page->setLayout('default');
  1150.                 $em $this->getDoctrine()->getManager();
  1151.                 $em->persist($Page);
  1152.                 $em->flush();
  1153.             }
  1154.             if((empty($Page->getSettings()) && $Page->getLanguage() != $this->language) || $Page->getSettings() != $this->Settings){
  1155.                 // Invalid page! STOP NOW!
  1156.                 // Try to find alternative page
  1157.                 /*$AltPage = $this->getDoctrine()->getRepository('CmsBundle:Page')->findOneBy(['slugkey' => $Page->getSlugKey(), 'language' => $this->language]);
  1158.                 if(!empty($AltPage)){
  1159.                     return $this->redirect($this->generateUrl('admin_page_edit', ['id' => $AltPage->getId()]));
  1160.                 }else{*/
  1161.                     return $this->redirect($this->generateUrl('admin_page'));
  1162.                 // }
  1163.             }
  1164.             $base_uri_tmp $this->Settings->getBaseUri();
  1165.             if(preg_match('/\/.*?$/'$base_uri_tmp)){
  1166.                 $base_uri substr($base_uri_tmp1) . '/';
  1167.                 $newSlug str_replace($base_uri''$Page->getSlug());
  1168.                 $Page->setSlug($newSlug);
  1169.             }
  1170.             $Page->setUrl($this->generateUrl('homepage') . $this->getDoctrine()->getRepository('CmsBundle:Page')->getSlugPathByPage($Page));
  1171.             $parents $Page->getParents();
  1172.             if(!empty($parents)){
  1173.                 foreach(array_reverse($parents) as $Parent){
  1174.                     $this->breadcrumbs->addRouteItem($Parent->getLabel(), "admin_page_edit", ['id' => $Parent->getId()]);
  1175.                 }
  1176.             }
  1177.             $this->breadcrumbs->addRouteItem($Page->getLabel(), "admin_page_edit");
  1178.             /*if($Page->getLanguage() != $this->language){
  1179.                 $TranslatedPage = $this->getDoctrine()->getRepository('CmsBundle:Page')->findOneBy(['base' => $Page, 'language' => $this->language]);
  1180.                 if(!empty($TranslatedPage)){
  1181.                     return $this->redirect($this->generateUrl('admin_page_edit', ['id' => $TranslatedPage->getId()]));
  1182.                 }else{
  1183.                     $Original = $this->getDoctrine()->getRepository('CmsBundle:Page')->find($id);
  1184.                     $Page = clone $Page;
  1185.                     $Page->setLanguage($this->language);
  1186.                     $Page->setBase($Original);
  1187.                 }
  1188.             }*/
  1189.             $ParentPage $Page->getPage();
  1190.             $found_main_content false;
  1191.             // Find page content sections for dynamically assign content in templates
  1192.             $layout $Page->getLayout();
  1193.             $layoutPath $this->containerInterface->get('kernel')->getProjectDir() . '/templates/layouts/';
  1194.             if(empty($layout)){
  1195.                 if($this->Settings){
  1196.                     if(!empty($this->Settings->getDefaultTemplate())){
  1197.                         $layout $this->Settings->getDefaultTemplate();
  1198.                     }
  1199.                 }
  1200.                 if(empty($layout)){
  1201.                     $layout 'default';
  1202.                 }
  1203.             }
  1204.             $layoutFile $layoutPath $layout '.html.twig';
  1205.             if(file_exists($layoutFile)){
  1206.                 $layoutData file_get_contents($layoutFile);
  1207.                 if(preg_match('/{%\s?block\s?body\s?%}{%\s?endblock\s?%}/'$layoutData)){
  1208.                     $pageSections['default'] = 'Pagina inhoud';
  1209.                 }
  1210.                 // {{pagecontent(PageObject: Page, locale: app.request.locale, id: 3)}}
  1211.                 if(preg_match_all('/{{.*?pagecontent\(.*?,.*?,.*?\'(.*?)\'.*?\).*?}}/'$layoutData$m)){
  1212.                     foreach($m[1] as $i => $key){
  1213.                         $keyLabel trim($key);
  1214.                         $key preg_replace('/[^0-9a-z-]*/'''str_replace(' ''-'strtolower($keyLabel)));
  1215.                         $pageSections[$key] = $keyLabel;
  1216.                     }
  1217.                 }
  1218.                 if(preg_match_all('/{{.*?pageblocks\(.*?,.*?,.*?\'(.*?)\'.*?\).*?}}/'$layoutData$m)){
  1219.                     foreach($m[1] as $i => $key){
  1220.                         $keyLabel trim($key);
  1221.                         $key preg_replace('/[^0-9a-z-]*/'''str_replace(' ''-'strtolower($keyLabel)));
  1222.                         $pageBlockSections[$key] = $keyLabel;
  1223.                     }
  1224.                 }
  1225.             }
  1226.         }else{
  1227.             // Add
  1228.             $Page = new \App\CmsBundle\Entity\Page();
  1229.             $Page->setLanguage($this->language);
  1230.             $Page->setSettings($this->Settings);
  1231.             $Page->setDateAdd(new \DateTime());
  1232.             $Page->setCritical(true);
  1233.             $Page->setCache(true);
  1234.             /* Don't embed default layout in pages themself, ask at "run-time" instead
  1235.             $dtpl = $this->Settings->getDefaultTemplate();
  1236.             if(!empty($dtpl)){
  1237.                 $Page->setLayout($dtpl);
  1238.             }*/
  1239.             $all $this->getDoctrine()->getRepository('CmsBundle:Page')->findAll();
  1240.             $Page->setSort(count($all));
  1241.             $this->breadcrumbs->addRouteItem($this->trans("Toevoegen", [], 'cms'), "admin_page_edit");
  1242.             $appendToParent $request->query->get('parent');
  1243.             if(!is_null($appendToParent)){
  1244.                 $addToParent $ParentPage;
  1245.                 $ParentPage $this->getDoctrine()->getRepository('CmsBundle:Page')->find($appendToParent);
  1246.                 $Page->setPage($ParentPage);
  1247.             }
  1248.             $new true;
  1249.         }
  1250.         /*$PageMediaDir = $this->getDoctrine()->getRepository('CmsBundle:MediaDir')->findOneByLabel($Page->getLabel());
  1251.         $pageMediaDirId = 0;
  1252.         if(!empty($PageMediaDir)){
  1253.             $pageMediaDirId = $PageMediaDir->getId();
  1254.         }*/
  1255.         $layoutPaths = [
  1256.             $this->containerInterface->get('kernel')->getProjectDir() . '/templates/blocks/',
  1257.         ];
  1258.         if (!$this->Settings->getIgnoreCmsBlocks()) {
  1259.             $layoutPaths array_merge$layoutPaths, [
  1260.                 $this->containerInterface->get('kernel')->getProjectDir() . '/src/CmsBundle/Resources/views/blocks/',
  1261.                 $this->containerInterface->get('kernel')->getProjectDir() . '/src/CmsBundle/Resources/views/blocksv2/'
  1262.             ]);
  1263.         }
  1264.         // Search for native blocks provided by bundles
  1265.         if(!empty($this->installed)){
  1266.             $bundleDir $this->containerInterface->get('kernel')->getProjectDir() . '/src/Trinity/';
  1267.             foreach($this->installed as $bundleKey){
  1268.                 $bundleRoot $bundleDir $bundleKey;
  1269.                 if(file_exists($bundleRoot '/Resources/views/Cms/Blocks')){
  1270.                     // Has custom layout dir
  1271.                     $layoutPaths[] = $bundleRoot '/Resources/views/Cms/Blocks/';
  1272.                 }
  1273.             }
  1274.         }
  1275.         $blockKeyToLabel = [];
  1276.         foreach($layoutPaths as $layoutPath){
  1277.             if(!file_exists($layoutPath)) continue;
  1278.             // $layoutPath = $this->containerInterface->get('kernel')->getProjectDir() . '/src/CmsBundle/Resources/views/blocks/';
  1279.             foreach(scandir($layoutPath) as $block_tpl){
  1280.                 if(is_dir($layoutPath.$block_tpl) || substr($block_tpl01) == '.' || substr($block_tpl, -2) == 'md') continue;
  1281.                 $content file_get_contents($layoutPath $block_tpl);
  1282.                 if(preg_match('/\{\#(.*?)\#\}/is'$content$m)){
  1283.                     $conf $m[1];
  1284.                     // $conf = trim($conf);
  1285.                     // $conf = preg_replace('/\\r|\\n/', '', $conf);
  1286.                     // $conf = preg_replace('/\s+/', ' ', $conf);
  1287.                     // echo '<pre>' . print_r($conf, 1) . '</pre>';
  1288.                     $conf json_decode($conf);
  1289.                     $category 'Ongesorteerd';
  1290.                     if(preg_match('/blocksv2/'$layoutPath)){
  1291.                         $category 'v2';
  1292.                     }
  1293.                     if(!empty($conf->category)){
  1294.                         $category $conf->category;
  1295.                     }
  1296.                     $tmpLabel $this->trans($conf->label'blokken');
  1297.                     $blockKeyToLabel[$conf->key] = $tmpLabel;
  1298.                     if(!empty($conf) && !isset($all_block_sections[$conf->key])){
  1299.                         if(!isset($block_sections[$category])){
  1300.                             $block_sections[$category] = [];
  1301.                         }
  1302.                         $block_sections[$category][$conf->key] = $conf;
  1303.                         $all_block_sections[$conf->key] = $conf;
  1304.                         ksort($block_sections[$category]);
  1305.                     }
  1306.                 }
  1307.             }
  1308.         }
  1309.         // dump($blockKeyToLabel);die();
  1310.         ksort($block_sections);
  1311.         ksort($all_block_sections);
  1312.         $parentpath '';
  1313.         if(is_object($ParentPage)){
  1314.             $parentpath $this->getDoctrine()->getRepository('CmsBundle:Page')->getTitlePathByPage($ParentPage' / ');
  1315.         }
  1316.         $em $this->getDoctrine()->getManager();
  1317.         $mediaParent $this->getDoctrine()->getRepository('CmsBundle:Mediadir')->findPathByName($em, (!empty($this->Settings->getHost()) ? $this->Settings->getHost() . '/' '') . $this->trans('Paginas', [], 'cms') . '/' $Page->getLabel(), $this->language);
  1318.         $pageMediaDirId $mediaParent->getId();
  1319.         if(!empty($_FILES)){
  1320.             $Parent null;
  1321.             $type '';
  1322.             if(isset($_FILES['image'])){
  1323.                 // Upload image
  1324.                 $file $_FILES['image'];
  1325.                 $type 'image';
  1326.             }
  1327.             if(!is_null($mediaParent)){
  1328.                 // Create UploadedFile-object
  1329.                 $UploadedFile = new UploadedFile($file['tmp_name'], $file['name'], $file['type'], (int)$file['error'], true );
  1330.                 $Media = new \App\CmsBundle\Entity\Media();
  1331.                 $Media->setParent($mediaParent);
  1332.                 $Media->setLabel($file['name']);
  1333.                 $Media->setDateAdd();
  1334.                 $Media->setFile($UploadedFile); // Link UploadedFile to the media entity
  1335.                 $Media->preUpload(); // Prepare file and path
  1336.                 $Media->upload(); // Upload actual file
  1337.                 $Media->setSize($file['size']);
  1338.                 if($type == 'image'){
  1339.                     if($Page->hasImage()){
  1340.                         $PrevMedia $Page->getImageObject();
  1341.                         try{
  1342.                             // $em->remove($PrevMedia);
  1343.                         }catch(\Exception $e){}
  1344.                     }
  1345.                     $Page->setImage($Media);
  1346.                 }
  1347.                 $em->persist($Media);
  1348.                 $em->persist($Page);
  1349.                 $em->flush();
  1350.                 return new JsonResponse(array('success' => true'type' => $type'image' => '/' $Media->getWebPath(), 'id' => $Media->getId()));
  1351.             }
  1352.             return new JsonResponse(array('success' => false));
  1353.         }
  1354.         // $Language = $this->getDoctrine()->getRepository('CmsBundle:Language')->findOneByLocale($request->getLocale());
  1355.         if($Page->getVisible() && $Page->getEnabled()){
  1356.             $Page->setShowInSitemap(true);
  1357.         }
  1358.         $availableRoles = [
  1359.             $this->trans('Gebruiker', [], 'cms') => 'ROLE_USER',
  1360.         ];
  1361.         $roles $this->getParameter('security.role_hierarchy.roles');
  1362.         foreach($roles as $role => $inherit){
  1363.             $roleLabel ucfirst(strtolower(str_replace('_'' 'str_replace('ROLE_'''$role))));
  1364.             if($roleLabel == 'User'){
  1365.                 $roleLabel 'Gebruiker';
  1366.             }
  1367.             $availableRoles[$roleLabel] = $role;
  1368.         }
  1369.         $saved false;
  1370.         if(!empty($_POST)){
  1371.             if(!empty($_POST['form'])){
  1372.                 $em $this->getDoctrine()->getManager();
  1373.                 // xxx niet gebruikt?
  1374.                 $Layout $this->getDoctrine()->getRepository('CmsBundle:Layout')->findOneBy([], ['id' => 'asc']);
  1375.                 $form $_POST['form'];
  1376.                 if(!isset($form['enabled']) && isset($form['visible'])){
  1377.                     unset($form['visible']);
  1378.                 }
  1379.                 if(!empty($form['option_title'])){ $Page->setOptionTitle($form['option_title']); }else{ $Page->setOptionTitle(false); }
  1380.                 if(!empty($form['option_subtitle'])){ $Page->setOptionSubtitle($form['option_subtitle']); }else{ $Page->setOptionSubtitle(false); }
  1381.                 if(!empty($form['option_subnavigation'])){ $Page->setOptionSubnavigation($form['option_subnavigation']); }else{ $Page->setOptionSubnavigation(false); }
  1382.                 if(!empty($form['option_breadcrumbs'])){ $Page->setOptionBreadcrumbs($form['option_breadcrumbs']); }else{ $Page->setOptionBreadcrumbs(false); }
  1383.                 $Page->setLabel($form['label']);
  1384.                 $Page->setTitle($form['title']);
  1385.                 $Page->setSubtitle($form['subtitle']);
  1386.                 $Page->setEnabled(isset($form['enabled']));
  1387.                 $Page->setVisible(isset($form['visible']));
  1388.                 $Page->setTplInject($form['tpl_inject']);
  1389.                 $Page->setPageType($form['page_type']);
  1390.                 $Page->setCustomUrl($form['custom_url']);
  1391.                 $Page->setTarget($form['target']);
  1392.                 $Page->setClasses($form['classes']);
  1393.                 if(isset($form['layout'])) $Page->setLayout($form['layout']);
  1394.                 $Page->setLayoutid($Layout);
  1395.                 $Page->setController('CmsBundle:page:page');
  1396.                 // Notify
  1397.                 if(isset($form['notify_type'])) $Page->setNotifyType($form['notify_type']);
  1398.                 $Page->setNotifyTelegramBot($form['notify_telegram_bot']);
  1399.                 $Page->setNotifyTelegramBotChatId($form['notify_telegram_bot_chat_id']);
  1400.                 $Page->setNotifyEmail($form['notify_email']);
  1401.                 if(!empty($form['notify_change'])){ $Page->setNotifyChange($form['notify_change']); }else{ $Page->setNotifyChange(false); }
  1402.                 if(!empty($form['notify_create_child'])){ $Page->setNotifyCreateChild($form['notify_create_child']); }else{ $Page->setNotifyCreateChild(false); }
  1403.                 if(!empty($form['notify_change_child'])){ $Page->setNotifyChangeChild($form['notify_change_child']); }else{ $Page->setNotifyChangeChild(false); }
  1404.                 if(isset($form['access'])) $Page->setAccess($form['access']);
  1405.                 $Page->setAccessFree(!empty($form['access_free']));
  1406.                 $Page->setAccessAllowLogin(!empty($form['access_allow_login']));
  1407.                 $Page->setAccessAltHome(!empty($form['access_alt_home']));
  1408.                 $Page->setAccessVisibleMenu(!empty($form['access_visible_menu']));
  1409.                 $Page->setAccessB2b(!empty($form['access_b2b']));
  1410.                 
  1411.                 if(isset($form['access_pwd'])){
  1412.                     $Page->setAccessPwd($form['access_pwd']);
  1413.                 }
  1414.                 /* $role_labels = array_values($availableRoles);
  1415.                 foreach($form['access_roles'] as $k => $v){
  1416.                     $form['access_roles'][$k] = $role_labels[$v];
  1417.                 } */
  1418.                 $Page->setAccessRoles((isset($form['access_roles']) ? $form['access_roles'] : []));
  1419.                 $Page->setShowInSitemap(!empty($form['show_in_sitemap']));
  1420.                 if ($this->get('security.authorization_checker')->isGranted('ROLE_SUPER_ADMIN')) {
  1421.                     $Page->setCache(!empty($form['cache']));
  1422.                     $Page->setCritical(!empty($form['critical']));
  1423.                 }
  1424.                 $Page->setRobots($form['robots']);
  1425.                 if (empty($form['slug'])) {
  1426.                     if (!empty($form['title'])) {
  1427.                         $slug $form['title'];
  1428.                     } else {
  1429.                         $slug $form['label'];
  1430.                     }
  1431.                     
  1432.                     $Page->setSlug($this->toAscii($slug)); // Make slug lowercase and remove chars
  1433.                 } else {
  1434.                     $Page->setSlug($this->toAscii($form['slug']));
  1435.                 }
  1436.                 $Page->setCacheData(null); // Clear page cache
  1437.                 $Page->setCricitalCss(null); // Clear critical Css
  1438.                 
  1439.                 // Store in database
  1440.                 $em->persist($Page);
  1441.                 $em->flush(); // Pre-flush to avoid error
  1442.                 $FoundMedia false;
  1443.                 if(!empty($_POST['link'])){
  1444.                     foreach($_POST['link'] as $k => $v){
  1445.                         if(!empty($v)){
  1446.                             $id = ($v);
  1447.                             $v \App\CmsBundle\Util\Util::dashesToCamelCase($ktrue);
  1448.                             $has 'has' $v;
  1449.                             $get 'get' $v 'Object';
  1450.                             $set 'set' $v '';
  1451.                             $FoundMedia $this->getDoctrine()->getRepository('CmsBundle:Media')->find($id);
  1452.                             if($FoundMedia){
  1453.                                 $Page->$set($FoundMedia);
  1454.                             }
  1455.                         }
  1456.                     }
  1457.                 }
  1458.                 if(!empty($_POST['delete']) && empty($FoundMedia)){
  1459.                     foreach($_POST['delete'] as $k => $v){
  1460.                         if(!empty($v)){
  1461.                             $v \App\CmsBundle\Util\Util::dashesToCamelCase($ktrue);
  1462.                             $has 'has' $v;
  1463.                             $get 'get' $v 'Object';
  1464.                             $set 'set' $v '';
  1465.                             if($Page->$has()){
  1466.                                 $PrevMedia $Page->$get();
  1467.                                 try{
  1468.                                     $Page->$set(null);
  1469.                                     // $em->remove($PrevMedia);
  1470.                                 }catch(\Exception $e){}
  1471.                             }
  1472.                         }
  1473.                     }
  1474.                 }
  1475.                 foreach($Page->getTags() as $Tag){ $Page->removeTag($Tag); }
  1476.                 if(!empty($_POST['form']['tags'])){
  1477.                     foreach($_POST['form']['tags'] as $value){
  1478.                         // Check if exists as ID
  1479.                         if(is_numeric($value)){
  1480.                             $Tag $this->getDoctrine()->getRepository('CmsBundle:Tag')->findOneById($value);
  1481.                         }
  1482.                         // Check if exists as label (newly linked)
  1483.                         else{
  1484.                             $Tag $this->getDoctrine()->getRepository('CmsBundle:Tag')->findOneByLabel($value);
  1485.                         }
  1486.                         if(empty($Tag)){
  1487.                             // Create new
  1488.                             $Tag = new \App\CmsBundle\Entity\Tag();
  1489.                             $Tag->setLabel($value);
  1490.                             $em->persist($Tag);
  1491.                         }
  1492.                         $Page->addTag($Tag);
  1493.                     }
  1494.                 }
  1495.                 $Page->setDateEdit(new \DateTime());
  1496.                 $currentBlockIds = (!empty($_POST['block_config']) ? array_keys($_POST['block_config']) : []);
  1497.                 if(!empty($Page) && !empty($Page->getBlocks())){
  1498.                     foreach($Page->getBlocks() as $Wrapper){
  1499.                         foreach($Wrapper->getBlocks() as $Block){
  1500.                             if(!in_array($Block->getId(), $currentBlockIds)){
  1501.                                 $Wrapper->removeBlock($Block);
  1502.                                 $em->remove($Block);
  1503.                             }
  1504.                         }
  1505.                         // Clear empty wrapper
  1506.                         if($Wrapper->getBlocks()->count() == 0){
  1507.                             $em->remove($Wrapper);
  1508.                         }
  1509.                     }
  1510.                     $em->flush();
  1511.                 }
  1512.                 if(!empty($_POST['block_wrappers'])){
  1513.                     foreach($_POST['block_wrappers'] as $index => $wrapper_id){
  1514.                         $wrapper_attr = (!empty($_POST['block_wrappers_attr'][$wrapper_id]) ? $_POST['block_wrappers_attr'][$wrapper_id] : []);
  1515.                         $wrapper_key = (!empty($wrapper_attr['key']) ? $wrapper_attr['key'] : '');
  1516.                         if(is_numeric($wrapper_id)){
  1517.                             // Existing
  1518.                             $BlockWrapper $this->getDoctrine()->getRepository('CmsBundle:PageBlockWrapper')->find($wrapper_id);
  1519.                         }else{
  1520.                             // New
  1521.                             $BlockWrapper = new \App\CmsBundle\Entity\PageBlockWrapper();
  1522.                             $BlockWrapper->setInternalId($wrapper_id);
  1523.                             $BlockWrapper->setPage($Page);
  1524.                             $BlockWrapper->setTemplateKey($wrapper_key);
  1525.                         }
  1526.                         if(!empty($_POST['wrapper_fields'][$wrapper_id])){
  1527.                             foreach($_POST['wrapper_fields'][$wrapper_id] as $field => $value){
  1528.                                 $act 'set' ucfirst($field);
  1529.                                 if(trim(strip_tags($value)) == 'Introductie tekst'){
  1530.                                     $value '';
  1531.                                 }
  1532.                                 if(trim(strip_tags($value)) == 'Titel'){
  1533.                                     $value '';
  1534.                                 }
  1535.                                 $BlockWrapper->$act($value);
  1536.                             }
  1537.                         }
  1538.                         $padding_fields = ['paddingTop''paddingRight''paddingBottom''paddingLeft'];
  1539.                         if(!empty($_POST['wrapper-config'][$wrapper_id])){                            
  1540.                             $BlockWrapper->setCssClass(null); 
  1541.                             foreach($_POST['wrapper-config'][$wrapper_id] as $field => $value){
  1542.                                 // Fallback for padding
  1543.                                 if(in_array($field$padding_fields) && $value !== && $value !== '0' && empty($value)){
  1544.                                     $value null;
  1545.                                 }elseif($field == "cssClass" && !empty($value)){ 
  1546.                                     $value implode(" ",$value);
  1547.                                 }
  1548.                                 $act 'set' ucfirst($field);
  1549.                                 $BlockWrapper->$act($value);
  1550.                             }
  1551.                         }
  1552.                         if(isset($_POST['wrapper-grid'][$wrapper_id])){
  1553.                             $BlockWrapper->setGridSize($_POST['wrapper-grid'][$wrapper_id]);
  1554.                         }else{
  1555.                             // $BlockWrapper->setGridSize(1);
  1556.                         }
  1557.                         $BlockWrapper->setEnabled(!empty($_POST['block_wrappers_enabled'][$wrapper_id]));
  1558.                         $BlockWrapper->setPos($index);
  1559.                         $em->persist($BlockWrapper);
  1560.                         $sort 0;
  1561.                         if(!empty($_POST['block'][$wrapper_id])){
  1562.                             foreach($_POST['block'][$wrapper_id] as $block_id){
  1563.                                 $block_attr = (!empty($_POST['block_attr'][$block_id]) ? $_POST['block_attr'][$block_id] : []);
  1564.                                 $block_key = (!empty($block_attr['key']) ? $block_attr['key'] : '');
  1565.                                 if(is_numeric($block_id)){
  1566.                                     // Existing
  1567.                                     $Block $this->getDoctrine()->getRepository('CmsBundle:PageBlock')->find($block_id);
  1568.                                 }else{
  1569.                                     // New
  1570.                                     $Block = new \App\CmsBundle\Entity\PageBlock();
  1571.                                     $Block->setInternalId($block_id);
  1572.                                     $Block->setWrapper($BlockWrapper);
  1573.                                     $Block->setTemplateKey($block_key);
  1574.                                 }
  1575.                                 $config = (!empty($_POST['block_config'][$block_id]) ? $_POST['block_config'][$block_id] : []);
  1576.                                 $req = (!empty($_POST['block_req'][$block_id]) ? $_POST['block_req'][$block_id] : '');
  1577.                                 // New data source
  1578.                                 if(!empty($_POST['block_data'][$block_id])){
  1579.                                     $data_src $_POST['block_data'][$block_id];
  1580.                                     if(($data json_decode($data_srctrue)) && $data){
  1581.                                         // Done, valid JSON
  1582.                                     }else{
  1583.                                         if($this->containerInterface->getParameter('kernel.environment') == 'dev'){
  1584.                                             // JSON error, dump when on dev mode
  1585.                                             // dump('JSON error'); dump($data_src); die();                                            
  1586.                                         }
  1587.                                         $data = [];
  1588.                                     }
  1589.                                 }else{
  1590.                                     $data = [];
  1591.                                 }
  1592.                                 $Block->setData($data);
  1593.                                 $contained = (!empty($_POST['block_contained'][$block_id]) ? $_POST['block_contained'][$block_id] : '');
  1594.                                 if(is_array($config)){
  1595.                                     $Block->setConfig($config);
  1596.                                 }
  1597.                                 // Clean block content for now
  1598.                                 $Block->setContent(null);
  1599.                                 $Block->setContentType(null);
  1600.                                 $Block->setBundle(null);
  1601.                                 $Block->setBundleLabel(null);
  1602.                                 $Block->setBundleData(null);
  1603.                                 if($contained){
  1604.                                     $Block->setContained($contained);
  1605.                                 }
  1606.                                 $blockType null;
  1607.                                 if(!empty($_POST['block_type'])){
  1608.                                     if(!empty($_POST['block_type'][$block_id])){
  1609.                                         $blockType $_POST['block_type'][$block_id][0];
  1610.                                     }
  1611.                                 }
  1612.                                 if(!empty($_POST['block_content'][$block_id])){
  1613.                                     // Block content
  1614.                                     $Block->setContent($_POST['block_content'][$block_id][0]);
  1615.                                     $Block->setContentType('text');
  1616.                                     if($blockType){
  1617.                                         $Block->setContentType($blockType);
  1618.                                     }
  1619.                                 }else if(!empty($_POST['block_bundle'][$block_id])){
  1620.                                     // Block bundle
  1621.                                     $bundle $_POST['block_bundle'][$block_id]['bundle'];
  1622.                                     $label $_POST['block_bundle'][$block_id]['label'];
  1623.                                     $data $_POST['block_bundle'][$block_id]['data'];
  1624.                                     $Block->setContent('<h1>' $label '</h1>');
  1625.                                     $Block->setContentType('bundle');
  1626.                                     $Block->setBundle($bundle);
  1627.                                     $Block->setBundleLabel($label);
  1628.                                     $Block->setBundleData($data);
  1629.                                 }
  1630.                                 $ct = (!empty($_POST['block_content'][$block_id][0]) ? $_POST['block_content'][$block_id][0] : '');
  1631.                                 if($req == 'media' || $req == 'medias' || preg_match('/^\d+,/'$ct)){
  1632.                                     // Virtually remove media
  1633.                                     foreach($Block->getAltMedia() as $m){
  1634.                                         $Block->removeAltMedia($m);
  1635.                                         $em->remove($m);
  1636.                                     }
  1637.                                     $ct $Block->getContent();
  1638.                                     foreach(explode(';'$ct) as $i => $l){
  1639.                                         $t explode(','$l);
  1640.                                         $mediaId = (int)$t[0];
  1641.                                         $Media $this->getDoctrine()->getRepository('CmsBundle:Media')->find($mediaId);
  1642.                                         if($i == 0){
  1643.                                             $Block->setMedia($Media);
  1644.                                         }else{
  1645.                                             $BlockMedia = new \App\CmsBundle\Entity\PageBlockMedia();
  1646.                                             $BlockMedia->setMedia($Media);
  1647.                                             // $BlockMedia->setPageBlock($Block);
  1648.                                             $em->persist($BlockMedia);
  1649.                                             $Block->addAltMedia($BlockMedia);
  1650.                                         }
  1651.                                     }
  1652.                                 }
  1653.                                 $Block->setPos($sort);
  1654.                                 $em->persist($Block);
  1655.                                 $sort++;
  1656.                             }
  1657.                         }
  1658.                     }
  1659.                     $em->flush();
  1660.                 }
  1661.             }
  1662.             $enabledContent = (!empty($_POST['enabled']) ? $_POST['enabled'] : array());
  1663.             if(!empty($_POST['content']['new'])){
  1664.                 foreach ($_POST['content']['new'] as $name => $content){
  1665.                     $PageContent = new \App\CmsBundle\Entity\PageContent();
  1666.                     $PageContent->setContent($content);
  1667.                     $PageContent->setPage($Page);
  1668.                     $PageContent->setName($name);
  1669.                     $PageContent->setPublished(array_key_exists($name$enabledContent));
  1670.                     $em->persist($PageContent);
  1671.                 }
  1672.             }
  1673.             if(!empty($_POST['content']['edit'])){
  1674.                 foreach ($_POST['content']['edit'] as $id => $content){
  1675.                     $PageContent $this->getDoctrine()->getRepository('CmsBundle:PageContent')->find($id);
  1676.                     $next_rev = ((int)$PageContent->getRevision() + 1);
  1677.                     if($content != $PageContent->getContent()){
  1678.                         // Content has changed
  1679.                         $PageContentRevision = clone $PageContent;
  1680.                         $PageContentRevision->setContent($content);
  1681.                         $PageContentRevision->setRevision($next_rev);
  1682.                         $PageContentRevision->setPublished(array_key_exists($PageContentRevision->getName(), $enabledContent));
  1683.                         $em->persist($PageContentRevision);
  1684.                     }elseif($content == $PageContent->getContent()){
  1685.                         // Content hasn't changed
  1686.                         if(!$PageContent->getPublished() && array_key_exists($PageContent->getName(), $enabledContent)){
  1687.                             // Publish without changes
  1688.                             $PageContent->setPublished(true);
  1689.                             $em->persist($PageContent);
  1690.                         }
  1691.                     }
  1692.                 }
  1693.             }
  1694.             /*$activeTags = array();
  1695.             if(!empty($_POST['tags'])){
  1696.                 foreach($_POST['tags'] as $taglabel){
  1697.                     $Tag = $this->getDoctrine()->getRepository('CmsBundle:Tag')->getOrCreateByLabel($taglabel);
  1698.                     $activeTags[] = $Tag->getId();
  1699.                     if(!$Page->hasTag($Tag)) $Page->addTag($Tag);
  1700.                 }
  1701.             }
  1702.             foreach($Page->getTags() as $Tag){
  1703.                 if(!in_array($Tag->getId(), $activeTags)){
  1704.                     $Page->removeTag($Tag);
  1705.                 }
  1706.             }*/
  1707.             $em->flush();
  1708.             $notifySend false;
  1709.             foreach($Page->getParents() as $Parent){
  1710.                 if($new && $Parent->getNotifyCreateChild()){
  1711.                     // Child created
  1712.                     $this->notify($Parent$this->Settings->getLabel() . "\n" 'De pagina \'' . ($Page->getPage() ? $parentpath ' / ' '') . $Page->getLabel() . '\' is toegevoegd.''Pagina toegevoegd');
  1713.                     $notifySend true;
  1714.                     break;
  1715.                 }else if(!$new && $Parent->getNotifyChangeChild()){
  1716.                     // Child changed
  1717.                     $this->notify($Parent$this->Settings->getLabel() . "\n" 'De pagina \'' . ($Page->getPage() ? $parentpath ' / ' '') . $Page->getLabel() . '\' is gewijzigd.''Pagina gewijzigd');
  1718.                     $notifySend true;
  1719.                     break;
  1720.                 }
  1721.             }
  1722.             if(!$notifySend && $Page->getNotifyChange()){
  1723.                 // Edit page
  1724.                 $this->notify($Page$this->Settings->getLabel() . "\n" 'De pagina \'' . ($Page->getPage() ? $parentpath ' / ' '') . $Page->getLabel() . '\' is gewijzigd.''Pagina gewijzigd');
  1725.             }
  1726.             // Store metadata/metatags
  1727.             if(!empty($_POST['metadata'])){
  1728.                 foreach($_POST['metadata'] as $metatagid => $value){
  1729.                     $Metatag $this->getDoctrine()->getRepository('CmsBundle:Metatag')->findOneById($metatagid);
  1730.                     $PageMetatag $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getPageMetatagByPageId($Metatag$Page->getId());
  1731.                     $PageMetatag->setPage($Page);
  1732.                     $PageMetatag->setMetatagid($Metatag);
  1733.                     $PageMetatag->setValue($value);
  1734.                     $em->persist($PageMetatag);
  1735.                 }
  1736.                 $em->flush();
  1737.                 $saved true;
  1738.             }
  1739.             $notifyEmail $this->language->getNotifyEmail();
  1740.             $targetLocale $this->language->getLocale();
  1741.             if(!empty($notifyEmail)){
  1742.                 $subject $this->trans('notify_page_create_subject', [], 'cms', [], $targetLocale);
  1743.                 $subject str_replace([
  1744.                     '((page_label))',
  1745.                 ], [
  1746.                     $Page->getLabel(),
  1747.                 ], $subject);
  1748.                 $body $this->trans('notify_page_create', [], 'cms', [], $targetLocale);
  1749.                 $body str_replace([
  1750.                     '((page_id))',
  1751.                     '((page_label))',
  1752.                     '((page_edit_url))',
  1753.                 ], [
  1754.                     $Page->getId(),
  1755.                     $Page->getLabel(),
  1756.                     $this->generateUrl('admin_page_edit', ['id' => $Page->getId()], UrlGenerator::ABSOLUTE_URL),
  1757.                 ], $body);
  1758.                 $mailer = clone $this->mailer;
  1759.                 $mailer->init();
  1760.                 $mailer->setSubject($this->Settings->getLabel() . ': ' $subject)
  1761.                         ->setTo($notifyEmail)
  1762.                         ->setTwigBody('emails/notify.html.twig', [
  1763.                             'label' => '',
  1764.                             'message' => nl2br($body)
  1765.                         ])
  1766.                         ->setPlainBody(strip_tags($body));
  1767.                 $status $mailer->execute_forced();
  1768.             }
  1769.             $Syslog = new Log();
  1770.             $Syslog->setUser($this->getUser());
  1771.             $Syslog->setUsername($this->getUser()->getUsername());
  1772.             $Syslog->setType('page');
  1773.             $Syslog->setStatus('info');
  1774.             $Syslog->setObjectId($Page->getId());
  1775.             $Syslog->setSettings($this->Settings);
  1776.             if($new){
  1777.                 $Syslog->setAction('add');
  1778.                 $Syslog->setMessage('Pagina \'' $Page->getLabel() . '\' toegevoegd.');
  1779.             }else{
  1780.                 $Syslog->setAction('update');
  1781.                 $Syslog->setMessage('Pagina \'' $Page->getLabel() . '\' gewijzigd.');
  1782.             }
  1783.             $this->em->persist($Syslog);
  1784.             $this->em->flush();
  1785.             // Request async critical CSS request
  1786.             $this->requestCriticalCss($request$Page);
  1787.             // scan for blocks used in the CMS and save this as a json
  1788.             $keys $this->getDoctrine()->getRepository(Page::class)->getUsedBlocksBySettings($this->Settings);
  1789.             file_put_contents($usedBlockJSONjson_encode($keys));
  1790.             // Clear cache
  1791.             // $this->clearcacheAction();
  1792.             if(!empty($_POST['template_save'])){
  1793.                 header('Location: /bundles/cms/cache.php?url=' urlencode($this->generateUrl('admin_page_savetemplate', ['id' => $id])));
  1794.                 exit;
  1795.             }elseif(empty($_POST['inline_save'])){
  1796.                 if(!$request->isXmlHttpRequest()) {
  1797.                     header('Location: /bundles/cms/cache.php?url=' urlencode($this->generateUrl('admin_page_critical_generate', ['pageid' => $Page->getId()])) . '?url=' urlencode($this->generateUrl('admin_page')));
  1798.                     exit;
  1799.                 }else{
  1800.                     $Page->setSlugkey('pages_' $Page->getSlug());
  1801.                     die(
  1802.                         $this->trans('<p>De pagina "<strong>%pagelabel%</strong>" is succesvol toegevoegd.</p>
  1803.                         <p>Dit scherm wordt binnen enkele ogenblikken vernieuwd.</p>', ['%pagelabel%' => $Page->getLabel()], 'cms') .
  1804.                         '<script>window.location.reload(false);</script>'
  1805.                     );
  1806.                 }
  1807.             }else{
  1808.                 header('Location: /bundles/cms/cache.php?url=' urlencode($this->generateUrl('admin_page_critical_generate', ['pageid' => $Page->getId()])) . '?url=' urlencode($this->generateUrl('admin_page_edit', ['id' => $Page->getId()])));
  1809.                 exit;
  1810.             }
  1811.         }
  1812.         $pageContents = array();
  1813.         $sectionKeys array_keys($pageSections);
  1814.         foreach($sectionKeys as $name){
  1815.             $pageContents[$name] = $this->getDoctrine()->getRepository('CmsBundle:PageContent')->findOneBy([
  1816.                 'page' => $Page,
  1817.                 'name' => $name,
  1818.             ], [
  1819.                 'revision' => 'desc'
  1820.             ]);
  1821.         }
  1822.         $layout_dir $this->containerInterface->get('kernel')->getProjectDir() . '/templates/layouts/';
  1823.         $layouts = [];
  1824.         foreach(scandir($layout_dir) as $dir){
  1825.             if(substr($dir01) == '.') continue;
  1826.             $layouts[str_replace('.html.twig'''$dir)] = str_replace('.html.twig'''$dir);
  1827.         }
  1828.         // Search for custom layouts provided by bundles
  1829.         if(!empty($this->installed)){
  1830.             $bundleDir $this->containerInterface->get('kernel')->getProjectDir() . '/src/Trinity/';
  1831.             foreach($this->installed as $bundleKey){
  1832.                 $bundleRoot $bundleDir $bundleKey;
  1833.                 if(file_exists($bundleRoot '/Resources/views/Cms/Layouts')){
  1834.                     // Has custom layout dir
  1835.                     foreach(scandir($bundleRoot '/Resources/views/Cms/Layouts') as $dir){
  1836.                         if(substr($dir01) == '.') continue;
  1837.                         $layouts[str_replace('.html.twig'''$dir)] = $bundleKey ':' str_replace('.html.twig'''$dir);
  1838.                     }
  1839.                 }
  1840.             }
  1841.         }
  1842.         $page_type_options = [
  1843.             $this->trans('Standaard', [], 'cms')                   => '',
  1844.             $this->trans('Externe URL', [], 'cms')                 => 'external',
  1845.             $this->trans('Eerste onderliggende pagina', [], 'cms') => 'child',
  1846.         ];
  1847.         $notify_type_options = [
  1848.             $this->trans('Standaard (e-mail)', [], 'cms') => 'email',
  1849.             $this->trans('Telegram', [], 'cms')           => 'telegram',
  1850.         ];
  1851.         $target_options = [
  1852.             $this->trans('Huidige pagina', [], 'cms') => '',
  1853.             $this->trans('Nieuwe pagina', [], 'cms')  => '_blank',
  1854.             $this->trans('Huidig frame', [], 'cms')   => '_parent',
  1855.             $this->trans('Negeer frames', [], 'cms')  => '_top',
  1856.         ];
  1857.         $accessOptions = [
  1858.             $this->trans('Iedereen', [], 'cms')                    => '',
  1859.             $this->trans('Met wachtwoord', [], 'cms')              => 'password',
  1860.             $this->trans('Alleen ingelogd', [], 'cms')             => 'login',
  1861.             $this->trans('Alleen uitgelogd', [], 'cms')            => 'no-login',
  1862.             $this->trans('Heeft niet een bepaalde rol', [], 'cms') => 'no-role',
  1863.         ];
  1864.         $allowCache false;
  1865.         if ($this->containerInterface->hasParameter('trinity_cache') && ($this->containerInterface->getParameter('trinity_cache') == 'true' || $this->containerInterface->getParameter('trinity_cache'))) {
  1866.             $allowCache true;
  1867.         }
  1868.         // dump($Page->getTags());die();
  1869.         $form $this->createFormBuilder($Page)
  1870.             ->add('label'TextType::class, array('label' => $this->trans('Interne titel', [], 'cms')))
  1871.             ->add('title'TextType::class, array('label' => $this->trans('Weergave titel / Meta title', [], 'cms'), 'attr' => ['class' => 'fld-seo-title']))
  1872.             ->add('subtitle'TextType::class, array('label' => $this->trans('Sub-titel', [], 'cms'), 'required' => false))
  1873.             ->add('slug'TextType::class, array('label' => $this->trans('URI', [], 'cms'), 'required' => false'attr' => ['class' => 'fld-seo-slug''placeholder' => $this->trans('Optioneel', [], 'cms')]))
  1874.             ->add('page_type'ChoiceType::class, array('label' => $this->trans('Soort pagina', [], 'cms'), 'required' => false'choices' => $page_type_options))
  1875.             ->add('target'ChoiceType::class, array('label' => $this->trans('Link doel', [], 'cms'), 'required' => false'choices' => $target_options))
  1876.             ->add('custom_url'TextType::class, array('label' => $this->trans('Externe URL', [], 'cms'), 'required' => false))
  1877.             ->add('enabled'CheckboxType::class, array('label' => $this->trans('Pagina inschakelen', [], 'cms'), 'required' => false'row_attr' => ['class' => 'page-chk']))
  1878.             ->add('visible'CheckboxType::class, array('label' => $this->trans('Pagina zichtbaar in menu', [], 'cms'), 'required' => false'row_attr' => ['class' => 'page-chk']))
  1879.             ->add('classes'TextType::class, array('label' => $this->trans('Additionele CSS classes', [], 'cms'), 'required' => false))
  1880.             ->add('layout'ChoiceType::class, array('label' => $this->trans('Layout', [], 'cms'), 'required' => false'choices' => $layouts'placeholder' => '[system specified layout]'))
  1881.             ->add('content'TextareaType::class, array('label' => $this->trans('Inhoud', [], 'cms'), 'attr' => array('class' => 'ckeditor')))
  1882.             ->add('tpl_inject'TextareaType::class, array('label' => $this->trans('Template content', [], 'cms'), 'required' => false'attr' => ['class' => '']))
  1883.             /* not used atm, so hide
  1884.             ->add('tags', EntityType::class, [
  1885.                 'label' => $this->trans('Tags', [], 'cms'),
  1886.                 'class' => Tag::class,
  1887.                 'choice_label' => 'label',
  1888.                 'required' => false,
  1889.                 'multiple' => true,
  1890.                 // 'expanded' => true,
  1891.                 'attr' => [
  1892.                     'class' => 'tag-selector'
  1893.                 ]
  1894.             ])
  1895.             */
  1896.             // Options
  1897.             ->add('option_title'CheckboxType::class, array('label' => $this->trans('Titel tonen', [], 'cms'), 'required' => false'row_attr' => ['class' => 'page-chk']))
  1898.             ->add('option_subtitle'CheckboxType::class, array('label' => $this->trans('Sub-titel tonen', [], 'cms'), 'required' => false'row_attr' => ['class' => 'page-chk']))
  1899.             ->add('option_subnavigation'CheckboxType::class, array('label' => $this->trans('Sub-menu tonen', [], 'cms'), 'required' => false'row_attr' => ['class' => 'page-chk']))
  1900.             ->add('option_breadcrumbs'CheckboxType::class, array('label' => $this->trans('Breadcrumbs tonen', [], 'cms'), 'required' => false'row_attr' => ['class' => 'page-chk']))
  1901.             ->add('option_hide_in_submenu'CheckboxType::class, array('label' => $this->trans('Verbergen in submenu', [], 'cms'), 'required' => false'row_attr' => ['class' => 'page-chk']))
  1902.             // Notify
  1903.             ->add('notify_change'CheckboxType::class, array('label' => $this->trans('Melding bij wijzigen pagina', [], 'cms'), 'required' => false'row_attr' => ['class' => 'page-chk']))
  1904.             ->add('notify_create_child'CheckboxType::class, array('label' => $this->trans('Melding bij aanmaken onderliggende pagina', [], 'cms'), 'required' => false'row_attr' => ['class' => 'page-chk']))
  1905.             ->add('notify_change_child'CheckboxType::class, array('label' => $this->trans('Melding bij wijzigen onderliggende pagina', [], 'cms'), 'required' => false))
  1906.             ->add('notify_type'ChoiceType::class, array('label' => $this->trans('Soort melding', [], 'cms'), 'required' => false'choices' => $notify_type_options))
  1907.             ->add('notify_telegram_bot'TextType::class, array('label' => $this->trans('Telegram bot ID', [], 'cms'), 'required' => false))
  1908.             ->add('notify_telegram_bot_chat_id'TextType::class, array('label' => $this->trans('Telegram chat ID', [], 'cms'), 'required' => false))
  1909.             ->add('notify_email'TextType::class, array('label' => $this->trans('Ontvanger (email)', [], 'cms'), 'required' => false))
  1910.             ->add('access'ChoiceType::class, array('label' => $this->trans('Wie kan deze pagina zien?', [], 'cms'), 'required' => false'choices' => $accessOptions))
  1911.             ->add('access_roles'ChoiceType::class, array('label' => $this->trans('Toegestane rechten', [], 'cms'), 'multiple' => true'expanded' => true'required' => false'choices' => $availableRoles))
  1912.             ->add('access_free'CheckboxType::class, array('label' => $this->trans('Beschikbaar zonder inloggen (overruled andere paginas)', [], 'cms'), 'required' => false'row_attr' => ['class' => 'page-chk']))
  1913.             ->add('access_allow_login'CheckboxType::class, array('label' => $this->trans('Inloggen toestaan', [], 'cms'), 'required' => false'row_attr' => ['class' => 'page-chk']))
  1914.             ->add('access_alt_home'CheckboxType::class, array('label' => $this->trans('Alternatief home', [], 'cms'), 'required' => false'row_attr' => ['class' => 'page-chk']))
  1915.             ->add('access_visible_menu'CheckboxType::class, array('label' => $this->trans('Pagina zichtbaar in navigatie', [], 'cms'), 'required' => false))
  1916.             ->add('access_pwd'TextType::class, array('label' => $this->trans('Pagina wachtwoord', [], 'cms'), 'required' => false))
  1917.             ->add('show_in_sitemap'CheckboxType::class, array('label' => $this->trans('Zichtbaar in sitemap', [], 'cms'), 'required' => false'row_attr' => ['class' => 'page-chk']))
  1918.             ->add('robots'ChoiceType::class, array(
  1919.                 "multiple" => false,
  1920.                 "expanded" => false,
  1921.                 "label" => $this->trans("Zoekmachines", [], 'cms'),
  1922.                 'required' => false,
  1923.                 "choices" => array(
  1924.                     $this->trans('- Standaard (systeem instelling) -', [], 'cms') => '',
  1925.                     $this->trans('Niet indexeren of volgen', [], 'cms') => 'noindex,nofollow',
  1926.                     $this->trans('Alleen indexeren', [], 'cms')         => 'index,nofollow',
  1927.                     $this->trans('Indexeren en volgen', [], 'cms')      => 'index,follow',
  1928.                 )
  1929.             ));
  1930.         $is_b2b false;
  1931.         $is_webshop false;
  1932.         if($this->Webshop){
  1933.             $is_webshop true;
  1934.             if(!empty($this->Webshop) && !empty($this->Webshop->getSettings())){
  1935.                 if($this->Webshop->getSettings()->getB2b()){
  1936.                     $is_b2b true;
  1937.                     $form $form->add('access_b2b'CheckboxType::class, array('label' => 'Enkel inloggen met een B2B (webshop) account''required' => false));
  1938.                 }
  1939.             }
  1940.         }
  1941.         if($allowCache){
  1942.             $form $form->add('cache'CheckboxType::class, array('label' => $this->trans('Pagina cache inschakelen', [], 'cms'), 'required' => false'row_attr' => ['class' => 'page-chk']));
  1943.             if ($this->get('security.authorization_checker')->isGranted('ROLE_SUPER_ADMIN')) {
  1944.                 $form $form->add('critical'CheckboxType::class, array('label' => $this->trans('Pagina cricital css genereren', [], 'cms'), 'required' => false'row_attr' => ['class' => 'page-chk']));
  1945.             }
  1946.         }
  1947.         $form $form->getForm();
  1948.         $allowCache false; try{ $allowCache $this->containerInterface->getParameter('trinity_cache'); }catch(\Exception $e){}
  1949.         $maxFileSize 10;
  1950.         try{
  1951.             $maxFileSize = (int)ini_get('upload_max_filesize');
  1952.         }catch(\Exception $e){
  1953.             // Nothing going on here
  1954.         }
  1955.         $pageMetatags   $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(0, (int)$Page->getId(), true);
  1956.         $systemMetatags $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(1falsefalse);
  1957.         $dev false;
  1958.         if($this->containerInterface->getParameter('kernel.environment') == 'dev'){
  1959.             $dev true;
  1960.         }
  1961.         // Reorder based on priority
  1962.         $prioList = [];
  1963.         foreach($block_sections as $cat => $blocks){
  1964.             foreach($blocks as $block){
  1965.                 $priority 0;
  1966.                 if(!empty($block->priority)){
  1967.                     $priority $block->priority;
  1968.                 }
  1969.                 $category '..';
  1970.                 if(!empty($block->category)){
  1971.                     $category $block->category;
  1972.                 }
  1973.                 $prioList[$priority][$category][$block->key] = $block;
  1974.                 ksort($prioList[$priority][$category]);
  1975.             }
  1976.         }
  1977.         krsort($prioList);
  1978.         $block_sections = [];
  1979.         foreach($prioList as $prio => $blocks_categorized){
  1980.             foreach($blocks_categorized as $blocklist){
  1981.                 foreach($blocklist as $block){
  1982.                     $category '..';
  1983.                     if(!empty($block->category)){
  1984.                         $category $block->category;
  1985.                     }
  1986.                     $block_sections[$category][$block->key] = $block;
  1987.                 }
  1988.             }
  1989.         }
  1990.         // Get block field translations
  1991.         $BackendLanguage $this->getDoctrine()->getRepository('CmsBundle:Language')->findOneByLocale($this->getUser()->getAdminLocale());
  1992.         $LanguageTranslation $this->getDoctrine()->getRepository('CmsBundle:LanguageTranslation')->findBy(['catalogue' => 'blocks''language' => $BackendLanguage]);
  1993.         $blockTranslationList = [];
  1994.         foreach($LanguageTranslation as $LT){
  1995.             $blockTranslationList[$LT->getLanguageToken()->getToken()] = $LT->getTranslation();
  1996.         }
  1997.         $allBlockCssClasses $this->getDoctrine()->getRepository('CmsBundle:PageBlockWrapper')->findAllCssClasses();
  1998.         if($request->isXmlHttpRequest()) {
  1999.             return $this->render('@Cms/page/edit.ajax.twig', array(
  2000.                 'form'                 => $form->createView(),
  2001.                 'tags'                 => $this->getDoctrine()->getRepository('CmsBundle:Tag')->findAll(),
  2002.                 'new'                  => $new,
  2003.                 'pageMediaDirId'       => $pageMediaDirId,
  2004.                 'Page'                 => $Page,
  2005.                 'pageContents'         => $pageContents,
  2006.                 'ParentPage'           => $ParentPage,
  2007.                 'dev'                  => $dev,
  2008.                 'parentpath'           => $parentpath,
  2009.                 'pageMetatags'         => $pageMetatags,
  2010.                 'systemMetatags'       => $systemMetatags,
  2011.                 'pageSections'         => $pageSections,
  2012.                 'blockKeyToLabel'      => $blockKeyToLabel,
  2013.                 'pageBlockSections'    => $pageBlockSections,
  2014.                 'block_sections'       => $block_sections,
  2015.                 'all_block_sections'   => $all_block_sections,
  2016.                 'blockTranslationList' => $blockTranslationList,
  2017.                 'ActivePage'           => $ActivePage,
  2018.                 'id'                   => (int)$id,
  2019.                 'maxFileSize'          => (int)$maxFileSize,
  2020.                 'saved'                => (bool)$saved,
  2021.                 'is_b2b'             => (bool)$is_b2b,
  2022.                 'ck_mediadir_id'       => $pageMediaDirId,
  2023.                 'allowCache'           => $allowCache,
  2024.                 'allBlockCssClasses'    => $allBlockCssClasses,
  2025.             ));
  2026.         }
  2027.         return $this->attributes(array(
  2028.             'form'                 => $form->createView(),
  2029.             'tags'                 => $this->getDoctrine()->getRepository('CmsBundle:Tag')->findAll(),
  2030.             'new'                  => $new,
  2031.             'pageMediaDirId'       => $pageMediaDirId,
  2032.             'Page'                 => $Page,
  2033.             'pageContents'         => $pageContents,
  2034.             'ParentPage'           => $ParentPage,
  2035.             'dev'                  => $dev,
  2036.             'parentpath'           => $parentpath,
  2037.             'pageMetatags'         => $pageMetatags,
  2038.             'systemMetatags'       => $systemMetatags,
  2039.             'pageSections'         => $pageSections,
  2040.             'blockKeyToLabel'      => $blockKeyToLabel,
  2041.             'pageBlockSections'    => $pageBlockSections,
  2042.             'mediaParent'          => $mediaParent,
  2043.             'block_sections'       => $block_sections,
  2044.             'all_block_sections'   => $all_block_sections,
  2045.             'blockTranslationList' => $blockTranslationList,
  2046.             'ActivePage'           => $ActivePage,
  2047.             'id'                   => (int)$id,
  2048.             'maxFileSize'          => (int)$maxFileSize,
  2049.             'saved'                => (bool)$saved,
  2050.             'is_b2b'             => (bool)$is_b2b,
  2051.             'pages'                => $this->getPagesByParentid(),
  2052.             'ck_mediadir_id'       => $pageMediaDirId,
  2053.             'allowCache'           => $allowCache,
  2054.             'usedBlocks'           => $usedBlocks,
  2055.             'allBlockCssClasses'    => $allBlockCssClasses,
  2056.         ));
  2057.     }
  2058.     /**
  2059.      * @Route("/admin/page/request_critical/{pageid}", name="admin_page_critical_generate")
  2060.      */
  2061.     public function requestCriticalAction(Request $request$pageid)
  2062.     {
  2063.         $Page $this->getDoctrine()->getRepository('CmsBundle:Page')->find($pageid);
  2064.         if(empty($Page)){
  2065.             header('Location: /bundles/cms/cache.php?url=' urlencode($this->generateUrl('admin_page')));
  2066.             exit;
  2067.         }
  2068.         // Request async critical CSS request
  2069.         $this->requestCriticalCss($request$Page);
  2070.         if(!empty($request->get('url'))){
  2071.             //Redirect to URL
  2072.             header('Location: /bundles/cms/cache.php?url=' $request->get('url'));
  2073.             exit;
  2074.         } else {
  2075.             //Redirect to Admin
  2076.             header('Location: /bundles/cms/cache.php?url=' urlencode($this->generateUrl('admin_page')));
  2077.             exit;
  2078.         }
  2079.     }
  2080.     /**
  2081.      * @Route("/admin/page/delete/{id}", name="admin_page_delete")
  2082.      * @Template()
  2083.      */
  2084.     public function deleteAction(Request $request$id null)
  2085.     {
  2086.         parent::init($request);
  2087.         // Check permissions
  2088.         if(!$this->getUser()->checkPermissions('ALLOW_PAGE')){
  2089.             parent::test_permissions($request$this->getUser());
  2090.             throw $this->createNotFoundException($this->trans('This feature does not exist', [], 'cms'));
  2091.         }
  2092.         $em $this->getDoctrine()->getManager();
  2093.         $Page $em->getRepository('CmsBundle:Page')->find($id);
  2094.         $pageLabel $Page->getLabel();
  2095.         if(!is_null($Page)){
  2096.             $ParentPage $Page->getPage();
  2097.             $parentpath '';
  2098.             if(is_object($ParentPage)){
  2099.                 $parentpath $this->getDoctrine()->getRepository('CmsBundle:Page')->getTitlePathByPage($ParentPage' / ');
  2100.             }
  2101.             $notifySend false;
  2102.             foreach($Page->getParents() as $Parent){
  2103.                 if($Parent->getNotifyChangeChild()){
  2104.                     // Child changed
  2105.                     $this->notify($Parent
  2106.                             $this->trans("%settingslabel%\nDe pagina \'%pagelabel%\' is verwijderd", ['%settingslabel%' => $this->Settings->getLabel(), '%pagelabel%' => ($Page->getPage() ? $parentpath ' / ' '') . $Page->getLabel()], 'cms'),
  2107.                             /*$this->Settings->getLabel() . "\n" . 'De pagina \'' . ($Page->getPage() ? $parentpath . ' / ' : '') . $Page->getLabel() . '\' is verwijderd.',*/
  2108.                             $this->trans('Pagina verwijderd', [], 'cms'));
  2109.                     $notifySend true;
  2110.                     break;
  2111.                 }
  2112.             }
  2113.             if(!$notifySend && $Page->getNotifyChange()){
  2114.                 // Edit page
  2115.                 $this->notify($Page,
  2116.                         $this->trans("%settingslabel%\nDe pagina \'%pagelabel%\' is verwijderd", ['%settingslabel%' => $this->Settings->getLabel(), '%pagelabel%' => ($Page->getPage() ? $parentpath ' / ' '') . $Page->getLabel()], 'cms'),
  2117.                         /*$this->Settings->getLabel() . "\n" . 'De pagina \'' . ($Page->getPage() ? $parentpath . ' / ' : '') . $Page->getLabel() . '\' is verwijderd.',*/
  2118.                         $this->trans('Pagina verwijderd', [], 'cms'));
  2119.             }
  2120.             $em $this->getDoctrine()->getManager();
  2121.             $em->remove($Page);
  2122.             $em->flush();
  2123.             // Clear cache
  2124.             $this->clearcacheAction();
  2125.             $Syslog = new Log();
  2126.             $Syslog->setUser($this->getUser());
  2127.             $Syslog->setUsername($this->getUser()->getUsername());
  2128.             $Syslog->setType('page');
  2129.             $Syslog->setStatus('info');
  2130.             $Syslog->setSettings($this->Settings);
  2131.             $Syslog->setAction('delete');
  2132.             $Syslog->setMessage('Pagina \'' $pageLabel '\' is verwijderd.');
  2133.             $em $this->getDoctrine()->getManager();
  2134.             $em->persist($Syslog);
  2135.             $em->flush();
  2136.         }
  2137.         header('Location: /bundles/cms/cache.php?url=' urlencode($this->generateUrl('admin_page')));
  2138.         exit;
  2139.         // return $this->redirect($this->generateUrl('admin_page'));
  2140.     }
  2141.     /**
  2142.      * @Route("/admin/page/permissions/{id}", name="admin_page_permissions")
  2143.      * @Template()
  2144.      */
  2145.     public function permissionsAction(Request $request$id null)
  2146.     {
  2147.         parent::init($request);
  2148.         $em $this->getDoctrine()->getManager();
  2149.         $Page $em->getRepository('CmsBundle:Page')->find($id);
  2150.         /*if(!is_null($Page)){
  2151.             $em = $this->getDoctrine()->getManager();
  2152.             $em->remove($Page);
  2153.             $em->flush();
  2154.         }*/
  2155.         return $this->attributes(array(
  2156.             'Page' => $Page,
  2157.         ));
  2158.     }
  2159.     /**
  2160.      * Convert to ASCII
  2161.      *
  2162.      * @param  string $str       Input string
  2163.      * @param  array  $replace   Replace these additional characters
  2164.      * @param  string $delimiter Space delimiter
  2165.      *
  2166.      * @return string
  2167.      */
  2168.     public function toAscii($str$replace=array(), $delimiter='-') {
  2169.         if( !empty($replace) ) {
  2170.             $str str_replace((array)$replace' '$str);
  2171.         }
  2172.         $slugify = new \Cocur\Slugify\Slugify();
  2173.         return $slugify->slugify($str$delimiter);
  2174.     }
  2175.     /**
  2176.      * Clear Symfony cache
  2177.      *
  2178.      * @return Response
  2179.      */
  2180.     public function clearcacheAction(){
  2181.         $realCacheDir $this->containerInterface->getParameter('kernel.cache_dir');
  2182.         // Page caching in prod
  2183.         $pageCacheFile str_replace('/dev''/prod'$realCacheDir) . '/';
  2184.         foreach(scandir($pageCacheFile) as $f){
  2185.             if(is_file($pageCacheFile $f) && preg_match('/page_structure$/'$f)){
  2186.                 if(file_exists($pageCacheFile $f)){
  2187.                     unlink($pageCacheFile $f); // Relete cache file
  2188.                 }
  2189.             }
  2190.         }
  2191.         $oldCacheDir substr($realCacheDir0, -1).('~' === substr($realCacheDir, -1) ? '+' '~');
  2192.         $filesystem $this->containerInterface->get('filesystem');
  2193.         if (!is_writable($realCacheDir)) { throw new \RuntimeException($this->trans('Unable to write in the "%directory%" directory', ['%directory%' => $realCacheDir], 'cms')); }
  2194.         if ($filesystem->exists($oldCacheDir)) { $filesystem->remove($oldCacheDir); }
  2195.         $kernel $this->containerInterface->get('kernel');
  2196.         $this->containerInterface->get('cache_clearer')->clear($realCacheDir);
  2197.         // This causes problems when the system doesn't have enough rights
  2198.         //$filesystem->remove($realCacheDir);
  2199.         return new Response();
  2200.     }
  2201.     protected $Settings null;
  2202.     protected $breadcrumbs null;
  2203.     protected $absoluteUrl '';
  2204.     protected $FirstPage null;
  2205.     public function initPaging(Request $request){
  2206.         parent::init($request);
  2207.         $em $this->getDoctrine()->getManager();
  2208.         if(is_null($this->Settings)) $this->Settings $em->getRepository('CmsBundle:Settings')->findByLanguage($this->languagestr_replace('www.'''$request->getHttpHost()));
  2209.         if(empty($this->Settings) || empty($this->Settings->getId())){
  2210.             // Try to find default settings (first one) and append host
  2211.             $tmpSettings $em->getRepository('CmsBundle:Settings')->findOneBy([], ['id' => 'asc']);
  2212.             if(!empty($tmpSettings) && empty($tmpSettings->getHost())){
  2213.                 $tmpSettings->setHost(str_replace('www.'''$request->getHttpHost()));
  2214.                 $em->persist($tmpSettings);
  2215.                 $em->flush();
  2216.                 $this->Settings $tmpSettings;
  2217.             }
  2218.             if(empty($this->Settings) || empty($this->Settings->getId())){
  2219.                 die($this->trans('Er zijn geen instellingen gevonden met de host:', [], 'cms') . '<br/><strong>' str_replace('www.'''$request->getHttpHost()) . '</strong>');
  2220.             }
  2221.         }
  2222.         if(is_null($this->Settings)) $this->Settings = new \App\CmsBundle\Entity\Settings();
  2223.         $this->absoluteUrl $request->getScheme() . '://' $request->getHttpHost() . $request->getBasePath();
  2224.         $this->FirstPage null;
  2225.         $tmp_pages $this->getDoctrine()->getRepository('CmsBundle:Page')->findBy(array('language' => $this->Settings->getLanguage(), 'settings' => $this->Settings'page' => null'base' => null'enabled' => true), array('sort' => 'ASC'), 1);
  2226.         if(!empty($tmp_pages)){
  2227.             $this->FirstPage $tmp_pages[0];
  2228.         }
  2229.         $this->clearWebshopSessionVars();
  2230.     }
  2231.     private function clearWebshopSessionVars(){
  2232.         if(in_array('WebshopBundle'$this->installed)){
  2233.             $this->get('session')->set($this->language->getLocale().'_ecomm_model'null);
  2234.             $this->get('session')->set($this->language->getLocale().'_ecomm_licenseplate'null);
  2235.             $this->get('session')->set($this->language->getLocale().'_ecomm_brand'null);
  2236.             $this->get('session')->set($this->language->getLocale().'_ecomm_spec_filter'null);
  2237.             $this->get('session')->set($this->language->getLocale().'_ecomm_filter'null);
  2238.             $this->get('session')->set($this->language->getLocale().'_ecomm_query'null);
  2239.             $this->get('session')->set($this->language->getLocale().'_ecomm_type'null);
  2240.         }
  2241.     }
  2242.     public function pageHandler($request){
  2243.         // Handle page stuff from the website
  2244.         if(isset($_GET['live_edit']) && is_numeric($_GET['live_edit'])){
  2245.             $this->containerInterface->get('session')->set('live_edit'$_GET['live_edit'] == 1);
  2246.         }
  2247.     }
  2248.     /**
  2249.      * @Route("/", name="homepage")
  2250.      */
  2251.     public function homepageAction(Request $request)
  2252.     {
  2253.         $this->init($request);
  2254.         $cacheAge $this->cache_page;
  2255.         $this->Timer->mark('Before loading page');
  2256.         $this->initPaging($request);
  2257.         $this->Timer->mark('After: initPaging');
  2258.         $this->pageHandler($request);
  2259.         $this->Timer->mark('After: pageHandler');
  2260.         $request->getSession()->set('webshop_locale'$request->getSession()->get('_locale'));
  2261.         $User $this->containerInterface->get('security.token_storage')->getToken()->getUser();
  2262.         $webshopUser null;
  2263.         $webshop_enabled false;
  2264.         if(in_array('WebshopBundle'$this->installed)){
  2265.             $webshop_enabled true;            
  2266.             $webshopUser $this->getDoctrine()->getRepository('TrinityWebshopBundle:User')->findOneByUser($this->getUser());
  2267.         }
  2268.         // Maintenance mode
  2269.         if($this->Settings->getMaintenance() && (!is_object($User) || (!$User->hasRole('ROLE_ADMIN') && !$User->hasRole('ROLE_SUPER_ADMIN')))){
  2270.             return $this->render('@Cms/maintain.html.twig', array(
  2271.                 'bodyClass'       => 'dynamic',
  2272.                 'webshop_enabled' => $webshop_enabled,
  2273.                 'webshopUser'      => $webshopUser,
  2274.                 'Settings'        => $this->Settings,
  2275.                 'metatags'        => $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(0, (int)$this->FirstPage->getId(), true),
  2276.                 'users'           => $this->getDoctrine()->getRepository('CmsBundle:User')->findAll(),
  2277.                 'systemMetatags'  => $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(1falsefalse),
  2278.             ));
  2279.         }
  2280.         // $this->breadcrumbs = $this->containerInterface->get("white_october_breadcrumbs");
  2281.         // $this->breadcrumbs->addItem($this->Settings->getLabel(), $this->containerInterface->get("router")->generate("homepage"));
  2282.         // Load actual homepage instead of dynamic page
  2283.         if( $request->attributes->get('_route') == 'homepage' ){
  2284.             // $this->breadcrumbs->addItem($Page->getTitle(), '/' . $Page->getSlug());
  2285.             if(!is_null($this->FirstPage)){
  2286.                 $allowCache false;
  2287.                 if ($this->containerInterface->hasParameter('trinity_cache') && ($this->containerInterface->getParameter('trinity_cache') == 'true' || $this->containerInterface->getParameter('trinity_cache'))) {
  2288.                     $allowCache true;
  2289.                 }
  2290.                 if(!empty($_GET['nocache']) || !empty($_GET['resetcache']) || !empty($_GET['timer']) || $this->containerInterface->getParameter('kernel.environment') == 'dev'){
  2291.                     $allowCache false;
  2292.                 }
  2293.                 if(!empty($_POST['form']) && !empty($_POST['form-bundle-submit'])){
  2294.                     $allowCache false;
  2295.                 }
  2296.                 if($this->Meta){
  2297.                     $this->Meta->registerView($request'page');
  2298.                 }
  2299.                 if($allowCache && $this->FirstPage->getCache()){
  2300.                     $cachedData $this->FirstPage->getCacheData($request->getRequestUri(), $this->cache_page);
  2301.                     if(!empty($cachedData)){
  2302.                         // Return cached data
  2303.                         echo $cachedData;
  2304.                         exit;
  2305.                     }
  2306.                 }
  2307.                 $metatags       $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(0, (int)$this->FirstPage->getId(), true);
  2308.                 $systemMetatags $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(1falsefalse);
  2309.                 if(!empty($this->FirstPage)){
  2310.                     if($this->FirstPage->getPageType() == 'external'){
  2311.                         $custom_url $this->FirstPage->getCustomUrl();
  2312.                         if(!empty($custom_url)){
  2313.                             header('Location:' $custom_url);
  2314.                             exit;
  2315.                         }
  2316.                     }
  2317.                 }
  2318.                 // VALIDATE
  2319.                 $access $this->FirstPage->getAccess();
  2320.                 $access_b2b $this->FirstPage->getAccessB2b();
  2321.                 if($access != null){
  2322.                     // Validate permissions
  2323.                     if($access == 'login'){
  2324.                         $checkRoles $this->FirstPage->getAccessRoles();
  2325.                         if($checkRoles){
  2326.                             if(!is_array($checkRoles)) $checkRoles = [$checkRoles];
  2327.                             $hasRoleAccess false;
  2328.                             $hasB2bAccess false;
  2329.                             foreach($checkRoles as $role){
  2330.                                 if($this->containerInterface->get('security.authorization_checker')->isGranted($role)){
  2331.                                     $hasRoleAccess true;
  2332.                                     break;
  2333.                                 }
  2334.                             }
  2335.                             if($hasRoleAccess){
  2336.                                 if($access_b2b && !$this->getUser()->getB2b()){
  2337.                                     // User is authenticated, b2b access is required, but user doesnt have it
  2338.                                     $hasRoleAccess false;
  2339.                                 }
  2340.                             }
  2341.                             if(!$hasRoleAccess){
  2342.                                 if ($this->FirstPage->getAccessAllowLogin()) {
  2343.                                     // LOGIN FORM
  2344.                                     $hasLoginInvalidRoles false;
  2345.                                     if($this->containerInterface->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')){
  2346.                                         $hasLoginInvalidRoles true;
  2347.                                     }
  2348.                                     $hasAltPage false;
  2349.                                     if($hasLoginInvalidRoles){
  2350.                                         // Invalid role for this page
  2351.                                         $pages $this->getDoctrine()->getRepository('CmsBundle:Page')->findBy(['settings' => $this->Settings'access_alt_home' => true]);
  2352.                                         foreach($pages as $PageCheck){
  2353.                                             $access $PageCheck->getAccess();
  2354.                                             if($access != null && $access == 'login'){
  2355.                                                 $checkRoles $PageCheck->getAccessRoles();
  2356.                                                 if($checkRoles){
  2357.                                                     if(!is_array($checkRoles)) $checkRoles = [$checkRoles];
  2358.                                                     $hasRoleAccess false;
  2359.                                                     foreach($checkRoles as $role){
  2360.                                                         if($this->get('security.authorization_checker')->isGranted($role)){
  2361.                                                             $hasRoleAccess true;
  2362.                                                             break;
  2363.                                                         }
  2364.                                                     }
  2365.                                                     if($hasRoleAccess){
  2366.                                                         $this->FirstPage $PageCheck;
  2367.                                                         $hasAltPage true;
  2368.                                                     }
  2369.                                                 }
  2370.                                             }
  2371.                                         }
  2372.                                     }
  2373.                                     if(!$hasAltPage){
  2374.                                         $lastUsername '';
  2375.                                         $error null;
  2376.                                         $LoginPage = clone $this->FirstPage;
  2377.                                         $LoginPage->setTitle($this->trans('Inloggen', [], 'frontend'$request->getLocale()));
  2378.                                         $LoginPage->setLabel($this->trans('Inloggen', [], 'frontend'$request->getLocale()));
  2379.                                         $LoginPage->requireAuth true;
  2380.                                         $LoginPage->isHome true;
  2381.                                         $webshopUser null;
  2382.                                         if(in_array('WebshopBundle'$this->installed)){            
  2383.                                             $webshopUser $this->getDoctrine()->getRepository('TrinityWebshopBundle:User')->findOneByUser($this->getUser());
  2384.                                         }
  2385.                                         return $this->parse'@Cms/page/page'$this->attributes([
  2386.                                             'loginform'            => true,
  2387.                                             'bodyClass'            => 'dynamic',
  2388.                                             'webshop_enabled'      => $webshop_enabled,
  2389.                                             'webshopUser'             => $webshopUser,
  2390.                                             'Page'                 => $LoginPage,
  2391.                                             'metatags'             => $metatags,
  2392.                                             'systemMetatags'       => $systemMetatags,
  2393.                                             'error'                => $error,
  2394.                                             'last_username'        => $lastUsername,
  2395.                                             'hasLoginInvalidRoles' => $hasLoginInvalidRoles,
  2396.                                         ]));
  2397.                                     }
  2398.                                 }else{
  2399.                                     throw $this->createAccessDeniedException('Permission denied');
  2400.                                 }
  2401.                             }
  2402.                         }
  2403.                     }elseif($access == 'no-login'){
  2404.                         if($this->containerInterface->get('security.authorization_checker')->isGranted('ROLE_USER')){
  2405.                             throw $this->createAccessDeniedException('Permission denied');
  2406.                         }
  2407.                     }
  2408.                 }
  2409.                 $content = array();
  2410.                 $Language $this->em->getRepository('CmsBundle:Language')->findByLocale($request->getLocale());
  2411.                 $contents $this->em->getRepository('CmsBundle:PageContent')->findBy([
  2412.                     'page' => $this->FirstPage,
  2413.                     // 'language' => $Language
  2414.                 ], [
  2415.                     'revision' => 'desc'
  2416.                 ]);
  2417.                 $used = [];
  2418.                 if(!empty($contents)){
  2419.                     foreach($contents as $PageContent){
  2420.                         if(!empty($_GET['rev']) && is_numeric($_GET['rev']) && $PageContent->getName() == 'default' && $PageContent->getRevision() != (int)$_GET['rev']){
  2421.                             continue;
  2422.                         }
  2423.                         if((empty($_GET['rev']) || $_GET['rev'] != $PageContent->getRevision()) && !$PageContent->getPublished()){
  2424.                             continue;
  2425.                         }
  2426.                         if(!in_array($PageContent->getName(), $used)){
  2427.                             if((int)$this->containerInterface->get('session')->get('live_edit') == 0){
  2428.                                 $ct $PageContent->getContent();
  2429.                                 $ct $this->parseModuleContent($ct, array(), $request);
  2430.                                 $ct $this->parseCmsUrls($ct);
  2431.                                 $PageContent->setContent($ct);
  2432.                             }
  2433.                             $content[$PageContent->getName()] = $PageContent;
  2434.                             $used[] = $PageContent->getName();
  2435.                         }
  2436.                     }
  2437.                 }
  2438.                 $extraPageJs = [];
  2439.                 $extraPageCss = [];
  2440.                 // Find bundles resources.json
  2441.                 $active_bundles = [];
  2442.                 if ($this->FirstPage->getBlocks()->count() > 0) {
  2443.                     foreach ($this->FirstPage->getBlocks() as $Wrapper) {
  2444.                         if ($Wrapper->getBlocks()->count() > 0) {
  2445.                             foreach ($Wrapper->getBlocks() as $Block) {
  2446.                                 if (!empty($Block->getBundleData()) ||  !empty($Block->getConfig())) {
  2447.                                     $bundledata json_decode($Block->getBundleData(), true);
  2448.                                     if (empty($bundledata) && !empty($Block->getConfig())) {
  2449.                                         $configText $Block->getConfig();
  2450.                                         if (isset($configText['text'])) {
  2451.                                             $configText $configText['text'];
  2452.                                             if (preg_match('/({(.*?)})/'$configText$match) == 1) {
  2453.                                                 $text json_decode($match[1], true);
  2454.                                                 if (!empty($text) && isset($text['bundlename'])) {
  2455.                                                     $bundledata $text;
  2456.                                                 }
  2457.                                             }
  2458.                                         }
  2459.                                     }
  2460.                                     
  2461.                                     if (!empty($bundledata)) {
  2462.                                         $bundleName $bundledata['bundlename'];
  2463.                                         try {
  2464.                                             $bundleName str_replace('Qinox''Trinity'$bundleName);
  2465.                                             $bundleControllerName str_replace('Trinity''App\\Trinity\\'$bundleName) . '\\Controller\\' preg_replace('/(Trinity|Bundle)/'''$bundleName) . 'Controller';
  2466.                                             // THIS IS HOMEPAGE
  2467.                                             if (method_exists($bundleControllerName'resourcesHandler')) {
  2468.                                                 $bundle_resources_file $bundleControllerName::resourcesHandler($this->Settings$bundledata$this->containerInterface->get('kernel')->getProjectDir());
  2469.                                                 if (!empty($bundle_resources_file))
  2470.                                                 {
  2471.                                                     $bundle_resources_file file_get_contents($bundle_resources_file);
  2472.                                                     $bundle_resources json_decode($bundle_resources_filetrue);
  2473.                                                     // is json_decode fails the content is null
  2474.                                                     if (!empty($bundle_resources))
  2475.                                                     {
  2476.                                                         if (isset($bundle_resources['scripts'])) {
  2477.                                                             foreach($bundle_resources['scripts'] as $script) {
  2478.                                                                 if(!in_array($script$extraPageJs)){
  2479.                                                                     $extraPageJs[] = $script;
  2480.                                                                 }
  2481.                                                             }
  2482.                                                         }
  2483.                                                         if (isset($bundle_resources['style'])) {
  2484.                                                             foreach($bundle_resources['style'] as $style) {
  2485.                                                                 if(!in_array($style$extraPageCss)){
  2486.                                                                     $extraPageCss[] = $style;
  2487.                                                                 }
  2488.                                                             }
  2489.                                                         }
  2490.                                                     }
  2491.                                                 }
  2492.                                                 if (!in_array($bundleName$active_bundles)) {
  2493.                                                     $active_bundles[] = $bundleName;
  2494.                                                 }
  2495.                                             }
  2496.                                         } catch (\Exception $e) {
  2497.                                         }
  2498.                                     }
  2499.                                 }
  2500.                             }
  2501.                         }
  2502.                     }
  2503.                 }
  2504.                 $this->FirstPage->isHome true;
  2505.                 $this->Timer->mark('Before returning page to front-end');
  2506.                 $webshopUser null;
  2507.                 if(in_array('WebshopBundle'$this->installed)){            
  2508.                     $webshopUser $this->getDoctrine()->getRepository('TrinityWebshopBundle:User')->findOneByUser($this->getUser());
  2509.                 }
  2510.                 $response $this->render('@Cms/page/page.html.twig'$this->attributes([
  2511.                     'bodyClass'       => 'dynamic',
  2512.                     'content'         => $content,
  2513.                     'webshop_enabled' => $webshop_enabled,
  2514.                     'webshopUser'      => $webshopUser,
  2515.                     'Page'            => $this->FirstPage,
  2516.                     'extraPageCss'    => $extraPageCss,
  2517.                     'extraPageJs'     => $extraPageJs,
  2518.                     'metatags'        => $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(0, (int)$this->FirstPage->getId(), true),
  2519.                     'users'           => $this->getDoctrine()->getRepository('CmsBundle:User')->findAll(),
  2520.                     'systemMetatags'  => $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(1falsefalse),
  2521.                     ])
  2522.                 );
  2523.                 $response $this->responseRewriteOutput($responsefalsefalse);
  2524.                 if ($this->containerInterface->getParameter('kernel.environment') == 'prod') {
  2525.                     if(empty($_POST['form']) && empty($_POST['form-bundle-submit'])){
  2526.                         $this->FirstPage->setCacheData($response->getContent(), $request->getRequestUri());
  2527.                     }
  2528.                 }
  2529. /*
  2530.                 $response->headers->set(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER, 'true');
  2531.                 $response->setPublic();
  2532.                 $response->setMaxAge($cacheAge);
  2533.                 $response->headers->addCacheControlDirective('must-revalidate');  
  2534.                 $response->setVary(array('Accept-Encoding', 'User-Agent'));
  2535.                 $response->headers->addCacheControlDirective('max-age', $cacheAge);
  2536.                 $response->setSharedMaxAge($cacheAge);
  2537. */
  2538.                 return $response;
  2539.             }
  2540.             return $this->render('@Cms/clean-install.html.twig', []);
  2541.         }
  2542.     }
  2543.     /**
  2544.      * Load dynamic page as defined in CmsBundle
  2545.      *
  2546.      * @param  Request $request
  2547.      * @Template()
  2548.      */
  2549.     public function pageAction(Request $request){
  2550.         $this->init($request);
  2551.         $cacheAge $this->cache_page;
  2552.         $this->Timer->reset();
  2553.         $this->Timer->mark('Before loading page');
  2554.         $Page $this->getDoctrine()->getRepository('CmsBundle:Page')->find($request->get('pageId'));
  2555.         // Check from parameters if caching must be enabled
  2556.         $allowCache false; try{ $allowCache $this->containerInterface->getParameter('trinity_cache'); }catch(\Exception $e){}
  2557.         if(!empty($_GET['nocache']) || !empty($_GET['resetcache']) || !empty($_GET['timer'])){
  2558.             $allowCache false;
  2559.         }
  2560.         if(!empty($_POST['form']) && !empty($_POST['form-bundle-submit'])){
  2561.             $allowCache false;
  2562.         }
  2563.         if($this->Meta){
  2564.             $this->Meta->registerView($request'page');
  2565.         }
  2566.         if($allowCache && $Page->getCache()){
  2567.             $cachedData $Page->getCacheData($request->getRequestUri(), $this->cache_page);
  2568.             if(!empty($cachedData)){
  2569.                 // Return cached data
  2570.                 echo $cachedData;
  2571.                 exit;
  2572.             }
  2573.         }
  2574.         $this->initPaging($request);
  2575.         $this->Timer->mark('After: initPaging');
  2576.         $this->pageHandler($request);
  2577.         $this->Timer->mark('After: pageHandler');
  2578.         $request->getSession()->set('webshop_locale'$request->getSession()->get('_locale'));
  2579.         $FirstPage null;
  2580.         $tmp_pages $this->getDoctrine()->getRepository('CmsBundle:Page')->findBy(array('page' => null'settings' => $this->Settings'enabled' => true), array('sort' => 'ASC'), 1);
  2581.         if(!empty($tmp_pages)){
  2582.             $FirstPage $tmp_pages[0];
  2583.         }
  2584.         $params = array();
  2585.         $params[] = $request->get('param1');
  2586.         $params[] = $request->get('param2');
  2587.         $params[] = $request->get('param3');
  2588.         $params[] = $request->get('param4');
  2589.         $params[] = $request->get('param5');
  2590.         $User $this->containerInterface->get('security.token_storage')->getToken()->getUser();
  2591.         // Maintenance mode
  2592.         if($this->Settings->getMaintenance() && (!is_object($User) || (!$User->hasRole('ROLE_ADMIN') && !$User->hasRole('ROLE_SUPER_ADMIN')))){
  2593.             return $this->render('@Cms/maintain.html.twig', array(
  2594.                 'Settings' => $this->Settings,
  2595.                 'users' => $this->getDoctrine()->getRepository('CmsBundle:User')->findAll()
  2596.             ));
  2597.         }
  2598.         if($Page->getSettings() && $Page->getSettings()->getId() != $this->Settings->getId()){
  2599.             // Found page doesn't share the proper settings ID, try to find another page with the same slug key and the proper settings ID
  2600.             $tmpSlugKey $Page->getSlugKey();
  2601.             $AltPage $this->getDoctrine()->getRepository('CmsBundle:Page')->findOneBy(['settings' => $this->Settings'slugkey' => $tmpSlugKey]);
  2602.             if($AltPage){
  2603.                 // Found alternative page on current site, moving..
  2604.                 $Page $AltPage;
  2605.             }else{
  2606.                 // Not found, page is not available for current settings
  2607.                 throw $this->createNotFoundException('Page not found');
  2608.             }
  2609.         }
  2610.         // Find alternative for language
  2611.         if($Page->getLanguage() != $this->language){
  2612.             $AltPage $this->getDoctrine()->getRepository('CmsBundle:Page')->findOneBy(['language' => $this->language'slugkey' => $Page->getSlugKey()]);
  2613.             if(!empty($AltPage)){
  2614.                 $Page $AltPage;
  2615.             }
  2616.         }
  2617.         if($Page->getPageType() == 'external'){
  2618.             header('Location:' $Page->getCustomUrl()); exit;
  2619.         }
  2620.         if($Page->getPageType() == 'child'){
  2621.             $ChildPage null;
  2622.             $childPages $Page->getPages();
  2623.             // Ignore disabled pages. If no valid childs are found, redirect to 'homepage'
  2624.             foreach($childPages as $p)
  2625.             {
  2626.                 if ($p->getEnabled() && $p->getLanguage() == $Page->getLanguage()) {
  2627.                     $ChildPage $p;
  2628.                     break;
  2629.                 }
  2630.             }
  2631.             if (empty($ChildPage)) {
  2632.                 header('Location:'.$this->generateUrl('homepage'));exit;
  2633.             }
  2634.             header('Location:' $this->generateUrl($ChildPage->getSlugKey())); exit;
  2635.         }
  2636.         if(!$Page->isValid() || $Page->getLanguage() != $this->language){
  2637.             throw $this->createNotFoundException($this->trans('Page not found', [], 'cms'));
  2638.         }
  2639.         if($Page == $FirstPage){
  2640.             // If active page and home page are identical, redirect to homepage
  2641.             $baseUri $this->Settings->getBaseUri();
  2642.             if(empty($baseUri)){
  2643.                 return $this->redirect($this->generateUrl('homepage'));
  2644.             }
  2645.         }
  2646.         $Parent $Page;
  2647.         $parent_crumbs = [];
  2648.         while($Parent->hasPage()){
  2649.             $Parent $Parent->getPage();
  2650.             $parent_crumbs[] = [$Parent->getLabel(), $Parent->getSlugKey()];
  2651.         }
  2652.         if(!empty($parent_crumbs)){
  2653.             $parent_crumbs array_reverse($parent_crumbs);
  2654.             foreach($parent_crumbs as $crumb){
  2655.                 $this->breadcrumbs->addRouteItem($crumb[0], $crumb[1]);
  2656.             }
  2657.         }
  2658.         $this->breadcrumbs->addItem($Page->getLabel(), $Page->getSlug());
  2659.         // $this->breadcrumbs->addItem($Page->getTitle(), '/' . $Page->getSlug());
  2660.         $metatags       $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(0, (int)$Page->getId(), true);
  2661.         $systemMetatags $this->getDoctrine()->getRepository('CmsBundle:Metatag')->getBySystem(1falsefalse);
  2662.         /* **** **** **** **** **** **** **** **** **** **** **** **** ****
  2663.             START | FIND ENTITIES RELATED TO METATAG
  2664.         **** **** **** **** **** **** **** **** **** **** **** **** **** */
  2665.         $linkedBundle null;
  2666.         $bundle_metatags = [];
  2667.         // Find first bundle linked on page        
  2668.         if($Page->getBlocks()->count() > 0){
  2669.             foreach($Page->getBlocks() as $Wrapper){
  2670.                 if($Wrapper->getBlocks()->count() > 0){
  2671.                     foreach($Wrapper->getBlocks() as $Block){
  2672.                         if(!empty($Block->getBundleData())){
  2673.                             $bundledata json_decode($Block->getBundleData(), true);
  2674.                             if(!empty($bundledata)){
  2675.                                 $bundleName $bundledata['bundlename'];
  2676.                                 try {
  2677.                                     $bundleName str_replace('Qinox''Trinity'$bundleName);
  2678.                                     $bundleControllerName str_replace('Trinity''App\\Trinity\\'$bundleName) . '\\Controller\\' preg_replace('/(Trinity|Bundle)/'''$bundleName) . 'Controller';
  2679.                                     $cleanUri preg_replace('/^\//'''str_replace($this->generateUrl($request->get('_route')), ''$this->uri));
  2680.                                     $params explode('/'$cleanUri);
  2681.                                     if(method_exists($bundleControllerName'metatagHandler')){
  2682.                                         $bundle_metatags $bundleControllerName::metatagHandler($this->em$params$bundledata$request);
  2683.                                         $linkedBundle str_replace('Trinity'''$Block->getBundle()); break 2;
  2684.                                     }
  2685.                                 } catch (\Symfony\Component\Debug\Exception\UndefinedMethodException $e) {
  2686.                                     
  2687.                                 }
  2688.                             }
  2689.                         }
  2690.                     }
  2691.                 }
  2692.             }
  2693.         }
  2694.         /* **** **** **** **** **** **** **** **** **** **** **** **** ****
  2695.             END | FIND ENTITIES RELATED TO METATAG
  2696.         **** **** **** **** **** **** **** **** **** **** **** **** **** */
  2697.         $blockData null;
  2698.         $content = array();
  2699.         $Language $this->em->getRepository('CmsBundle:Language')->findByLocale($request->getLocale());
  2700.         $contents $this->em->getRepository('CmsBundle:PageContent')->findBy([
  2701.             'page' => $Page,
  2702.             // 'language' => $Language
  2703.         ], [
  2704.             'revision' => 'desc'
  2705.         ]);
  2706.         $used = [];
  2707.         $blocks $Page->getBlocks();
  2708.         $ct '';
  2709.         if($Page->getAccessFree()){
  2710.             // No login required
  2711.         }else{
  2712.             $CheckPage null;
  2713.             foreach($Page->getParents($this->FirstPage) as $Parent){
  2714.                 // VALIDATE
  2715.                 $access $Parent->getAccess();
  2716.                 $access_b2b $Parent->getAccessB2b();
  2717.                 if($access != null){
  2718.                     // Validate permissions
  2719.                     if($access == 'password'){
  2720.                         if ($this->get('session')->get('page-auth') == $Page->getId()) {
  2721.                             // Succes
  2722.                         }else{
  2723.                             // PASSWORD FORM
  2724.                             $LoginPage = clone $Parent;
  2725.                             $LoginPage->setTitle($this->trans('Inloggen', [], 'frontend'$request->getLocale()));
  2726.                             $LoginPage->setLabel($this->trans('Inloggen', [], 'frontend'$request->getLocale()));
  2727.                             $LoginPage->requireAuth true;
  2728.                             $error null;
  2729.                             if(!empty($_POST['_password'])){
  2730.                                 if($_POST['_password'] == $LoginPage->getAccessPwd()){
  2731.                                     $this->get('session')->set('page-auth'$Page->getId());
  2732.                                     header('Location:' $this->generateUrl($Page->getSlugKey()));
  2733.                                     exit;
  2734.                                 }else{
  2735.                                     $error $this->trans('Het wachtwoord is ongeldig.', [], 'cms');
  2736.                                 }
  2737.                             }
  2738.                             return $this->attributes([
  2739.                                 'pwdform'            => true,
  2740.                                 'bodyClass'            => 'dynamic',
  2741.                                 'Page'                 => $LoginPage,
  2742.                                 'metatags'             => $metatags,
  2743.                                 'systemMetatags'       => $systemMetatags,
  2744.                                 'bundle_metatags'      => $bundle_metatags,
  2745.                                 'error'                => $error,
  2746.                             ]);
  2747.                         }
  2748.                     }elseif($access == 'login'){
  2749.                         $checkRoles $Parent->getAccessRoles();
  2750.                         if($checkRoles){
  2751.                             if(!is_array($checkRoles)) $checkRoles = [$checkRoles];
  2752.                             $hasRoleAccess false;
  2753.                             foreach($checkRoles as $role){
  2754.                                 if($this->containerInterface->get('security.authorization_checker')->isGranted($role)){
  2755.                                     $hasRoleAccess true;
  2756.                                     break;
  2757.                                 }
  2758.                             }
  2759.                             if($hasRoleAccess){
  2760.                                 if($access_b2b && !$this->getUser()->getB2b()){
  2761.                                     // User is authenticated, b2b access is required, but user doesnt have it
  2762.                                     $hasRoleAccess false;
  2763.                                 }
  2764.                             }
  2765.                             if(!$hasRoleAccess){
  2766.                                 if ($Parent->getAccessAllowLogin()) {
  2767.                                     // LOGIN FORM
  2768.                                     $LoginPage = clone $Parent;
  2769.                                     $hasLoginInvalidRoles false;
  2770.                                     if($this->containerInterface->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')){
  2771.                                         $hasLoginInvalidRoles true;
  2772.                                     }
  2773.                                     $lastUsername '';
  2774.                                     $error null;
  2775.                                     $LoginPage->setTitle($this->trans('Inloggen', [], 'frontend'$request->getLocale()));
  2776.                                     $LoginPage->setLabel($this->trans('Inloggen', [], 'frontend'$request->getLocale()));
  2777.                                     $LoginPage->requireAuth true;
  2778.                                     return $this->attributes([
  2779.                                         'loginform'            => true,
  2780.                                         'bodyClass'            => 'dynamic',
  2781.                                         'Page'                 => $LoginPage,
  2782.                                         'metatags'             => $metatags,
  2783.                                         'systemMetatags'       => $systemMetatags,
  2784.                                         'bundle_metatags'      => $bundle_metatags,
  2785.                                         'error'                => $error,
  2786.                                         'last_username'        => $lastUsername,
  2787.                                         'hasLoginInvalidRoles' => $hasLoginInvalidRoles,
  2788.                                     ]);
  2789.                                 }else{
  2790.                                     throw $this->createAccessDeniedException($this->trans('Permission denied'));
  2791.                                 }
  2792.                             }
  2793.                         }
  2794.                     }elseif($access == 'no-login'){
  2795.                         if($this->containerInterface->get('security.authorization_checker')->isGranted('ROLE_USER')){
  2796.                             throw $this->createAccessDeniedException($this->trans('Permission denied', [], 'cms'));
  2797.                         }
  2798.                     }
  2799.                 }
  2800.             }
  2801.             // VALIDATE
  2802.             $access $Page->getAccess();
  2803.             $access_b2b $Page->getAccessB2b();
  2804.             if($access != null){
  2805.                 // Validate permissions
  2806.                 if($access == 'password'){
  2807.                     if ($this->get('session')->get('page-auth') == $Page->getId()) {
  2808.                         // Succes
  2809.                     }else{
  2810.                         // PASSWORD FORM
  2811.                         $LoginPage = clone $Page;
  2812.                         $LoginPage->setTitle($this->trans('Inloggen', [], 'frontend'$request->getLocale()));
  2813.                         $LoginPage->setLabel($this->trans('Inloggen', [], 'frontend'$request->getLocale()));
  2814.                         $LoginPage->requireAuth true;
  2815.                         $error null;
  2816.                         if(!empty($_POST['_password'])){
  2817.                             if($_POST['_password'] == $LoginPage->getAccessPwd()){
  2818.                                 $this->get('session')->set('page-auth'$Page->getId());
  2819.                                 header('Location:' $this->generateUrl($Page->getSlugKey()));
  2820.                                 exit;
  2821.                             }else{
  2822.                                 $error $this->trans('Het wachtwoord is ongeldig.', [], 'cms');
  2823.                             }
  2824.                         }
  2825.                         return $this->attributes([
  2826.                             'pwdform'            => true,
  2827.                             'bodyClass'            => 'dynamic',
  2828.                             'Page'                 => $LoginPage,
  2829.                             'metatags'             => $metatags,
  2830.                             'systemMetatags'       => $systemMetatags,
  2831.                             'bundle_metatags'      => $bundle_metatags,
  2832.                             'error'                => $error,
  2833.                         ]);
  2834.                     }
  2835.                 }elseif($access == 'login'){
  2836.                     $checkRoles $Page->getAccessRoles();
  2837.                     if($checkRoles){
  2838.                         if(!is_array($checkRoles)) $checkRoles = [$checkRoles];
  2839.                         $hasRoleAccess false;
  2840.                         foreach($checkRoles as $role){
  2841.                             if($this->containerInterface->get('security.authorization_checker')->isGranted($role)){
  2842.                                 $hasRoleAccess true;
  2843.                                 break;
  2844.                             }
  2845.                         }
  2846.                         if($hasRoleAccess){
  2847.                             if($access_b2b && !$this->getUser()->getB2b()){
  2848.                                 // User is authenticated, b2b access is required, but user doesnt have it
  2849.                                 $hasRoleAccess false;
  2850.                             }
  2851.                         }
  2852.                         if(!$hasRoleAccess){
  2853.                             if ($Page->getAccessAllowLogin()) {
  2854.                                 // LOGIN FORM
  2855.                                 $hasLoginInvalidRoles false;
  2856.                                 if($this->containerInterface->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')){
  2857.                                     $hasLoginInvalidRoles true;
  2858.                                 }
  2859.                                 $lastUsername '';
  2860.                                 $error null;
  2861.                                 $LoginPage = clone $Page;
  2862.                                 $LoginPage->setTitle($this->trans('Inloggen', [], 'frontend'$request->getLocale()));
  2863.                                 $LoginPage->setLabel($this->trans('Inloggen', [], 'frontend'$request->getLocale()));
  2864.                                 $LoginPage->requireAuth true;
  2865.                                 return $this->attributes([
  2866.                                     'loginform'            => true,
  2867.                                     'bodyClass'            => 'dynamic',
  2868.                                     'Page'                 => $LoginPage,
  2869.                                     'metatags'             => $metatags,
  2870.                                     'systemMetatags'       => $systemMetatags,
  2871.                                     'bundle_metatags'      => $bundle_metatags,
  2872.                                     'error'                => $error,
  2873.                                     'last_username'        => $lastUsername,
  2874.                                     'hasLoginInvalidRoles' => $hasLoginInvalidRoles,
  2875.                                 ]);
  2876.                             }else{
  2877.                                 throw $this->createAccessDeniedException($this->trans('Permission denied', [], 'cms'));
  2878.                             }
  2879.                         }
  2880.                     }
  2881.                 }elseif($access == 'no-login'){
  2882.                     if($this->containerInterface->get('security.authorization_checker')->isGranted('ROLE_USER')){
  2883.                         throw $this->createAccessDeniedException($this->trans('Permission denied', [], 'cms'));
  2884.                     }
  2885.                 }
  2886.             }
  2887.         }
  2888.         // VALIDATE
  2889.         $access $Page->getAccess();
  2890.         $access_b2b $Page->getAccessB2b();
  2891.         if($access != null){
  2892.             // Validate permissions
  2893.                 if($access == 'password'){
  2894.                     if ($this->get('session')->get('page-auth') == $Page->getId()) {
  2895.                         // Succes
  2896.                     }else{
  2897.                         // PASSWORD FORM
  2898.                         $LoginPage = clone $Page;
  2899.                         $LoginPage->setTitle($this->trans('Inloggen', [], 'frontend'$request->getLocale()));
  2900.                         $LoginPage->setLabel($this->trans('Inloggen', [], 'frontend'$request->getLocale()));
  2901.                         $LoginPage->requireAuth true;
  2902.                         $error null;
  2903.                         if(!empty($_POST['_password'])){
  2904.                             if($_POST['_password'] == $LoginPage->getAccessPwd()){
  2905.                                 $this->get('session')->set('page-auth'$Page->getId());
  2906.                                 header('Location:' $this->generateUrl($Page->getSlugKey()));
  2907.                                 exit;
  2908.                             }else{
  2909.                                 $error $this->trans('Het wachtwoord is ongeldig.', [], 'cms');
  2910.                             }
  2911.                         }
  2912.                         return $this->attributes([
  2913.                             'pwdform'            => true,
  2914.                             'bodyClass'            => 'dynamic',
  2915.                             'Page'                 => $LoginPage,
  2916.                             'metatags'             => $metatags,
  2917.                             'systemMetatags'       => $systemMetatags,
  2918.                             'bundle_metatags'      => $bundle_metatags,
  2919.                             'error'                => $error,
  2920.                         ]);
  2921.                     }
  2922.                 }elseif($access == 'login'){
  2923.                 $checkRoles $Page->getAccessRoles();
  2924.                 if($checkRoles){
  2925.                     if(!is_array($checkRoles)) $checkRoles = [$checkRoles];
  2926.                     $hasRoleAccess false;
  2927.                     foreach($checkRoles as $role){
  2928.                         if($this->containerInterface->get('security.authorization_checker')->isGranted($role)){
  2929.                             $hasRoleAccess true;
  2930.                             break;
  2931.                         }
  2932.                     }
  2933.                     if($hasRoleAccess){
  2934.                         if($access_b2b && !$this->getUser()->getB2b()){
  2935.                             // User is authenticated, b2b access is required, but user doesnt have it
  2936.                             $hasRoleAccess false;
  2937.                             if(!$hasRoleAccess){
  2938.                                 if ($this->FirstPage->getAccessAllowLogin()) {
  2939.                                     // LOGIN FORM
  2940.                                     $hasLoginInvalidRoles false;
  2941.                                     if($this->containerInterface->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')){
  2942.                                         $hasLoginInvalidRoles true;
  2943.                                     }
  2944.                                     $hasAltPage false;
  2945.                                     if($hasLoginInvalidRoles){
  2946.                                         // Invalid role for this page
  2947.                                         $pages $this->getDoctrine()->getRepository('CmsBundle:Page')->findBy(['settings' => $this->Settings'access_alt_home' => true]);
  2948.                                         foreach($pages as $PageCheck){
  2949.                                             $access $PageCheck->getAccess();
  2950.                                             if($access != null && $access == 'login'){
  2951.                                                 $checkRoles $PageCheck->getAccessRoles();
  2952.                                                 if($checkRoles){
  2953.                                                     if(!is_array($checkRoles)) $checkRoles = [$checkRoles];
  2954.                                                     $hasRoleAccess false;
  2955.                                                     foreach($checkRoles as $role){
  2956.                                                         if($this->get('security.authorization_checker')->isGranted($role)){
  2957.                                                             $hasRoleAccess true;
  2958.                                                             break;
  2959.                                                         }
  2960.                                                     }
  2961.                                                     if($hasRoleAccess){
  2962.                                                         $this->FirstPage $PageCheck;
  2963.                                                         $hasAltPage true;
  2964.                                                     }
  2965.                                                 }
  2966.                                             }
  2967.                                         }
  2968.                                     }
  2969.                                     if(!$hasAltPage){
  2970.                                         $lastUsername '';
  2971.                                         $error null;
  2972.                                         $LoginPage = clone $this->FirstPage;
  2973.                                         $LoginPage->setTitle($this->trans('Inloggen', [], 'frontend'$request->getLocale()));
  2974.                                         $LoginPage->setLabel($this->trans('Inloggen', [], 'frontend'$request->getLocale()));
  2975.                                         $LoginPage->requireAuth true;
  2976.                                         return $this->parse'@Cms/Page/page'$this->attributes([
  2977.                                             'loginform'            => true,
  2978.                                             'bodyClass'            => 'dynamic',
  2979.                                             'Page'                 => $LoginPage,
  2980.                                             'metatags'             => $metatags,
  2981.                                             'systemMetatags'       => $systemMetatags,
  2982.                                             'bundle_metatags'      => $bundle_metatags,
  2983.                                             'error'                => $error,
  2984.                                             'last_username'        => $lastUsername,
  2985.                                             'hasLoginInvalidRoles' => $hasLoginInvalidRoles,
  2986.                                         ]));
  2987.                                     }
  2988.                                 }else{
  2989.                                     throw $this->createAccessDeniedException($this->trans('Permission denied', [], 'cms'));
  2990.                                 }
  2991.                             }
  2992.                         }
  2993.                     }elseif($access == 'no-login'){
  2994.                         if($this->containerInterface->get('security.authorization_checker')->isGranted('ROLE_USER')){
  2995.                             throw $this->createAccessDeniedException($this->trans('Permission denied', [], 'cms'));
  2996.                         }
  2997.                     }
  2998.                 }
  2999.             }
  3000.         }
  3001.         if(!empty($contents)){
  3002.             foreach($contents as $PageContent){
  3003.                 if(!empty($_GET['rev']) && is_numeric($_GET['rev']) && $PageContent->getName() == 'default' && $PageContent->getRevision() != (int)$_GET['rev']){
  3004.                     continue;
  3005.                 }
  3006.                 if((empty($_GET['rev']) || $_GET['rev'] != $PageContent->getRevision()) && !$PageContent->getPublished()){
  3007.                     continue;
  3008.                 }
  3009.                 if(!in_array($PageContent->getName(), $used)){
  3010.                     if((int)$this->containerInterface->get('session')->get('live_edit') == 0){
  3011.                         $ct $PageContent->getContent();
  3012.                         $ct $this->parseModuleContent($ct$params$request);
  3013.                         if(preg_match_all('/\[page:([a-zA-Z0-9\-\_]+)(\#[a-zA-Z0-9\-].*?)?\]/'$ct$matches)){
  3014.                             $idToSlug = [];
  3015.                             $cacheFile preg_replace('/\/src.*/''/var/cache/prod/'__DIR__) . 'page_id_slug';
  3016.                             if(file_exists($cacheFile)){
  3017.                                 $idToSlug json_decode(file_get_contents($cacheFile), true);
  3018.                             }
  3019.                             foreach($matches[0] as $index => $tag){
  3020.                                 $key $matches[1][$index];
  3021.                                 if(is_numeric($key)){ if(array_key_exists($key$idToSlug)){ $key $idToSlug[$key]; }else{ $key 'homepage'; } }
  3022.                                 $key str_replace('-''_'$key);
  3023.                                 $ct str_replace('http://' $tag$this->generateUrl($key), $ct);
  3024.                                 $ct str_replace('https://' $tag$this->generateUrl($key), $ct);
  3025.                                 $ct str_replace($tag$this->generateUrl($key), $ct);
  3026.                             }
  3027.                         }
  3028.                         $PageContent->setContent($ct);
  3029.                     }
  3030.                     $content[$PageContent->getName()] = $PageContent;
  3031.                     $used[] = $PageContent->getName();
  3032.                 }
  3033.             }
  3034.         }
  3035.         // Check for alt names
  3036.         $customTitle null;
  3037.         $page_locale $Page->getLanguage()->getLocale();
  3038.         $realCacheDir preg_replace('/\/cache.*/''/cache/prod/'$this->containerInterface->getParameter('kernel.cache_dir'));
  3039.         foreach(scandir($realCacheDir) as $file){
  3040.             if(is_file($realCacheDir.$file) && substr($file07) == 'titles_'){
  3041.                 $fd file($realCacheDir.$file);
  3042.                 foreach($fd as $line){
  3043.                     $line explode("\t"$line);
  3044.                     if($page_locale == trim($line[0])){
  3045.                         $uri str_replace('/' $Page->getSlug(), ''$_SERVER['REQUEST_URI']);
  3046.                         if(strpos(trim($uri), trim($line[1])) !== false){
  3047.                             $customTitle trim($line[2]) . ' - ';
  3048.                         }
  3049.                     }
  3050.                 }
  3051.             }
  3052.         }
  3053.         $extraPageJs = [];
  3054.         $extraPageCss = [];
  3055.         // Find bundles resources.json
  3056.         $active_bundles = [];
  3057.         if ($Page->getBlocks()->count() > 0) {
  3058.             foreach ($Page->getBlocks() as $Wrapper) {
  3059.                 if ($Wrapper->getBlocks()->count() > 0) {
  3060.                     foreach ($Wrapper->getBlocks() as $Block) {
  3061.                         if (!empty($Block->getBundleData())) {
  3062.                             $bundledata json_decode($Block->getBundleData(), true);
  3063.                             if (!empty($bundledata)) {
  3064.                                 $bundleName $bundledata['bundlename'];
  3065.                                 try {
  3066.                                     $bundleName str_replace('Qinox''Trinity'$bundleName);
  3067.                                     $bundleControllerName str_replace('Trinity''App\\Trinity\\'$bundleName) . '\\Controller\\' preg_replace('/(Trinity|Bundle)/'''$bundleName) . 'Controller';
  3068.                                     // THIS IS REGULAR PAGE
  3069.                                     if (method_exists($bundleControllerName'resourcesHandler')) {
  3070.                                         $bundle_resources_file $bundleControllerName::resourcesHandler($this->Settings$bundledata$this->containerInterface->get('kernel')->getProjectDir());
  3071.                                         // dump($bundle_resources_file); die();
  3072.                                         if (!empty($bundle_resources_file))
  3073.                                         {
  3074.                                             $bundle_resources_file file_get_contents($bundle_resources_file);
  3075.                                             $bundle_resources json_decode($bundle_resources_filetrue);
  3076.                                             // is json_decode fails the content is null
  3077.                                             if (!empty($bundle_resources))
  3078.                                             {
  3079.                                                 if (isset($bundle_resources['scripts'])) {
  3080.                                                     foreach($bundle_resources['scripts'] as $script) {
  3081.                                                         if(!in_array($script$extraPageJs)){
  3082.                                                             $extraPageJs[] = $script;
  3083.                                                         }
  3084.                                                     }
  3085.                                                 }
  3086.                                                 if (isset($bundle_resources['style'])) {
  3087.                                                     foreach($bundle_resources['style'] as $style) {
  3088.                                                         if(!in_array($style$extraPageCss)){
  3089.                                                             $extraPageCss[] = $style;
  3090.                                                         }
  3091.                                                     }
  3092.                                                 }
  3093.                                             }
  3094.                                         }
  3095.                                         if (!in_array($bundleName$active_bundles)) {
  3096.                                             $active_bundles[] = $bundleName;
  3097.                                         }
  3098.                                     }
  3099.                                 } catch (\Exception $e) {
  3100.                                 }
  3101.                             }
  3102.                         }
  3103.                     }
  3104.                 }
  3105.             }
  3106.         }
  3107.         
  3108.         $this->containerInterface->get('session')->set('last-route'$request->get('_route'));
  3109.         $this->Timer->mark('Before returning page to front-end');
  3110.         $webshopUser null;
  3111.         $webshop_enabled false;
  3112.         if(in_array('WebshopBundle'$this->installed)){
  3113.             $webshop_enabled true;            
  3114.             $webshopUser $this->getDoctrine()->getRepository('TrinityWebshopBundle:User')->findOneByUser($this->getUser());
  3115.         }
  3116.         $response $this->render('@Cms/page/page.html.twig'$this->attributes([
  3117.             'bodyClass'      => 'dynamic',
  3118.             'webshopUser'    => $webshopUser,
  3119.             'Page'           => $Page,
  3120.             'extraPageCss'   => $extraPageCss,
  3121.             'extraPageJs'    => $extraPageJs,
  3122.             'params'         => $params,
  3123.             'customTitle'    => $customTitle,
  3124.             'blockData'      => $blockData,
  3125.             'content'        => $content,
  3126.             'metatags'       => $metatags,
  3127.             'systemMetatags' => $systemMetatags,
  3128.             'bundle_metatags' => $bundle_metatags,
  3129.             'users'          => $this->getDoctrine()->getRepository('CmsBundle:User')->findAll(),
  3130.             'timer_result'    => $this->Timer->show(false),
  3131.         ]));
  3132.         $response $this->responseRewriteOutput($responsetrue);
  3133. /*
  3134.         $response->headers->set(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER, 'true');
  3135.         $response->setPublic();
  3136.         $response->setMaxAge($cacheAge);
  3137.         $response->headers->addCacheControlDirective('must-revalidate');  
  3138.         $response->setVary(array('Accept-Encoding', 'User-Agent'));
  3139.         $response->headers->addCacheControlDirective('max-age', $cacheAge);
  3140.         $response->setSharedMaxAge($cacheAge);
  3141. */
  3142.         if ($this->containerInterface->getParameter('kernel.environment') == 'prod') {
  3143.             if(empty($_POST['form']) && empty($_POST['form-bundle-submit'])){
  3144.                 $Page->setCacheData($response->getContent(), $request->getRequestUri());
  3145.             }
  3146.         }
  3147.         return $response;
  3148.     }
  3149.     private function parseModuleContent($content$params = array(), $request null){
  3150.         // $content = '[app.show_form:show(2)]'; // Form
  3151.         // $content = '[app.show_blog:show(1)]'; // Blog
  3152.         if(preg_match_all('/\[(.*?_show):(.*?)\((.*?)\)\]/'$content$m)){
  3153.             foreach($m[1] as $i => $call){
  3154.                 $action $m[2][$i];
  3155.                 $value $m[3][$i];
  3156.                 $cfg json_decode($valuetrue);
  3157.                 if(is_null($cfg)) $cfg = array();
  3158.                 try{
  3159.                     $func $action 'Action';
  3160.                     $content str_replace($m[0][$i], $this->containerInterface->get($call)->$func($cfg$params$request), $content);
  3161.                 }catch(\Exception $e){
  3162.                     $content str_replace($m[0][$i], $e->getMessage(), $content);
  3163.                 }
  3164.             }
  3165.         }
  3166.         return $content;
  3167.     }
  3168.     /**
  3169.      * @Route("/admin/page/link/{plugin}", name="admin_page_link")
  3170.      * @Template()
  3171.      */
  3172.     public function linkAction(Request $requestEnvironment $twig$plugin null){
  3173.         parent::init($request);
  3174.         $routes $this->modRoutes;
  3175.         /* foreach($routes as $index => $route){
  3176.             if(!$this->containerInterface->get('templating')->exists($route['bundleName'] . '::link.html.twig')){
  3177.                 unset($routes[$index]);
  3178.             }
  3179.         } */
  3180.         $linkdata = array();
  3181.         $activeRoute null;
  3182.         if($plugin != null){
  3183.             foreach($routes as $route){
  3184.                 if($plugin == $route['name']){
  3185.                     $activeRoute $route; break;
  3186.                 }
  3187.             }
  3188.             if(in_array(strtolower($plugin), ['trinity''admin'])){
  3189.                 $route = [
  3190.                     'name' => 'Admin',
  3191.                     'route' => 'admin',
  3192.                     'bundleName' => 'admin'
  3193.                 ];
  3194.                 $activeRoute $route;
  3195.             }
  3196.             if(!empty($activeRoute)){
  3197.                 $LinkController $this->containerInterface->get(strtolower($activeRoute['bundleName']) . '_link');
  3198.                 $linkdata $LinkController->getLinkData($this->getDoctrine(), $this->language$this->containerInterface$this->Settings);
  3199.             }
  3200.         }
  3201.         return $this->attributes([
  3202.             'activeRoute' => $activeRoute,
  3203.             'routes' => $routes,
  3204.             'linkdata' => $linkdata,
  3205.             'post' => (!empty($_POST) && !isset($_POST['init']) ? $_POST null),
  3206.             'poststring' => (!empty($_POST) ? json_encode($_POST) : json_encode([]))
  3207.         ]);
  3208.     }
  3209.     /**
  3210.      * @Route("/admin/page/copy/{locale}", name="admin_page_copy")
  3211.      * @Template()
  3212.      */
  3213.     public function copyAction(Request $request$locale null$parent null$newParent null$depth 0){
  3214.         parent::init($request);
  3215.         /*if($depth > 5){
  3216.             die("DEPTH ERROR!!!");
  3217.         }*/
  3218.         // Multisite import
  3219.         if(!empty($_POST['pages']) && empty($parent)){
  3220.             foreach($_POST['pages'] as $pageid){
  3221.                 $OriginalPage $this->em->getRepository('CmsBundle:Page')->find($pageid);
  3222.                 $NewPage = clone $OriginalPage;
  3223.                 $NewPage->setPage($newParent);
  3224.                 $NewPage->setLanguage($this->language);
  3225.                 $NewPage->setSettings($this->Settings);
  3226.                 if(isset($_POST['layout'])){
  3227.                     $NewPage->setLayout($_POST['layout']);
  3228.                 }
  3229.                 $this->em->persist($NewPage);
  3230.                 foreach($OriginalPage->getContent() as $Content){
  3231.                     $NewContent = clone $Content;
  3232.                     $NewContent->setPage($NewPage);
  3233.                     $this->em->persist($NewContent);
  3234.                 }
  3235.                 if(!empty($_POST['include-childs'])){
  3236.                     $this->copyAction($request$NewPage->getLanguage()->getLocale(), $OriginalPage$NewPage, ($depth 1));
  3237.                 }
  3238.             }
  3239.             $this->em->flush();
  3240.             if(empty($parent)){
  3241.                 ?>
  3242.                 U wordt doorgestuurd...
  3243.                 <script>
  3244.                     window.location.reload(true);
  3245.                 </script>
  3246.                 <?php
  3247.                 die();
  3248.             }
  3249.         }
  3250.         if(!empty($locale)){
  3251.             // Locale is now settings ID
  3252.             $Settings $this->em->getRepository('CmsBundle:Settings')->find($locale);
  3253.             $Language $Settings->getLanguage();
  3254.             $pages $this->em->getRepository('CmsBundle:Page')->findBy([
  3255.                 'settings' => $Settings,
  3256.                 'page' => $parent
  3257.             ], [
  3258.                 'sort' => 'asc'
  3259.             ]);
  3260.             if(!empty($pages)){
  3261.                 foreach($pages as $Page){
  3262.                     $NewPage = clone $Page;
  3263.                     $NewPage->setPage($newParent);
  3264.                     $NewPage->setLanguage($this->language);
  3265.                     $NewPage->setSettings($this->Settings);
  3266.                     if(isset($_POST['layout'])){
  3267.                         $NewPage->setLayout($_POST['layout']);
  3268.                     }
  3269.                     $this->em->persist($NewPage);
  3270.                     foreach($Page->getContent() as $Content){
  3271.                         $NewContent = clone $Content;
  3272.                         $NewContent->setPage($NewPage);
  3273.                         $this->em->persist($NewContent);
  3274.                     }
  3275.                     $this->copyAction($request$locale$Page$NewPage, ($depth 1));
  3276.                 }
  3277.             }
  3278.             $this->em->flush();
  3279.             return $this->redirect($this->generateUrl('admin_page'));
  3280.         }
  3281.         $layout_dir $this->containerInterface->get('kernel')->getProjectDir() . '/templates/layouts/';
  3282.         $layouts = [];
  3283.         foreach(scandir($layout_dir) as $dir){
  3284.             if(substr($dir01) == '.') continue;
  3285.             $layouts[str_replace('.html.twig'''$dir)] = str_replace('.html.twig'''$dir);
  3286.         }
  3287.         return $this->attributes(['layouts' => $layouts]);
  3288.     }
  3289.     /**
  3290.      * @Route("/admin/page/block-preview/{id}", name="admin_page_block_preview")
  3291.      */
  3292.     public function blockpreviewAction(Request $request$id){
  3293.         parent::init($request);
  3294.         return $this->redirect($this->generateUrl('admin_page'));
  3295.     }
  3296.     /**
  3297.      * @Route("/admin/page/clone/{id}", name="admin_page_clone")
  3298.      * @Template()
  3299.      */
  3300.     public function cloneAction(Request $request$id ''){
  3301.         parent::init($request);
  3302.         $ActivePage $this->em->getRepository(Page::class)->find($id);
  3303.         $PossibleParent $ActivePage->getPage();
  3304.         $error null;
  3305.         if(!empty($_POST)){
  3306.             $title $ActivePage->getLabel() . ' ' $this->trans('(kopie)', [], 'cms');
  3307.             if(!empty($_POST['title'])){
  3308.                 $title $_POST['title'];
  3309.             }
  3310.             if($ActivePage->getLabel() == $title){
  3311.                 // Duplicate label
  3312.                 $title $ActivePage->getLabel() . ' ' $this->trans('(kopie)', [], 'cms');
  3313.             }
  3314.             $em $this->getDoctrine()->getManager();
  3315.             $ActivePage->clone_type $_POST['content'];
  3316.             $ActivePage->em $em;
  3317.             $refId $id;
  3318.             $notifyEmail null;
  3319.             $targetLocale null;
  3320.             $slug $this->toAscii($title);
  3321.             $checkForSlug $this->em->getRepository(Page::class)->findOneBy(['slug' => $slug]);
  3322.             if(!empty($checkForSlug)){
  3323.                 // Found existing page with slug, add "-kopie" to the slug
  3324.                 $slug $slug '-kopie';
  3325.             }
  3326.             $Page = clone $ActivePage;
  3327.             $Page->setPage(null);
  3328.             $Page->setLabel($title);
  3329.             $Page->setTitle($title);
  3330.             $Page->setVisible(false);
  3331.             $Page->setSlug($slug);
  3332.             if(!empty($_POST['languageid'])){
  3333.                 $ChosenLanguage $this->em->getRepository('CmsBundle:Language')->find($_POST['languageid']);
  3334.                 $notifyEmail $ChosenLanguage->getNotifyEmail();
  3335.                 $targetLocale $ChosenLanguage->getLocale();
  3336.                 $Page->setLanguage($ChosenLanguage);
  3337.                 if(count($this->multisite) <= 1){
  3338.                     $Page->setSettings($ChosenLanguage->getSettings()->first());
  3339.                 }
  3340.                 // Set reference page
  3341.                 $Page->setRefId($refId);
  3342.                 if($Page->getPage()){
  3343.                     // This is sub
  3344.                     $foundParent null;
  3345.                     $pagesByLanguage $ChosenLanguage->getPages();
  3346.                     foreach($pagesByLanguage as $P){
  3347.                         if($P->getRefId() == $Page->getPage()->getId()){
  3348.                             $foundParent $P;
  3349.                             break;
  3350.                         }
  3351.                     }
  3352.                     $Page->setPage($foundParent);
  3353.                 }
  3354.             }
  3355.             if(!empty($_POST['multisite_id'])){
  3356.                 $Settings $this->getDoctrine()->getRepository('CmsBundle:Settings')->find($_POST['multisite_id']);
  3357.                 $Page->setSettings($Settings);
  3358.                 $Page->setLanguage($Settings->getLanguage());
  3359.             }
  3360.             $all $this->getDoctrine()->getRepository('CmsBundle:Page')->findAll();
  3361.             $sort count($all);
  3362.             $Page->setSort($sort);
  3363.             
  3364.             if(isset($_POST['visible'])){
  3365.                 $Page->setVisible(true);
  3366.             }
  3367.             $em->persist($Page);
  3368.             // Children
  3369.             if(isset($_POST['childs'])){
  3370.                 foreach($ActivePage->getPages() as $Child){
  3371.                     $NewChild = clone $Child;
  3372.                     $NewChild->setPage($Page);
  3373.                     $NewChild->setSort($sort += 1);
  3374.                     $em->persist($NewChild);
  3375.                     foreach($Child->getPages() as $SubChild){
  3376.                         $NewSubChild = clone $SubChild;
  3377.                         $NewSubChild->setPage($NewChild);
  3378.                         $NewSubChild->setSort($sort += 2);
  3379.                         $em->persist($NewSubChild);
  3380.                         foreach($SubChild->getPages() as $SubSubChild){
  3381.                             $NewSubSubChild = clone $SubSubChild;
  3382.                             $NewSubSubChild->setPage($NewSubChild);
  3383.                             $NewSubSubChild->setSort($sort += 2);
  3384.                             $em->persist($NewSubSubChild);
  3385.                         }
  3386.                     }
  3387.                 }
  3388.             }
  3389.             $em->flush();
  3390.             if(!empty($notifyEmail)){
  3391.                 $subject $this->trans('notify_page_copy_subject', [], 'cms'$targetLocale);
  3392.                 $subject str_replace([
  3393.                     '((page_label))',
  3394.                 ], [
  3395.                     $Page->getLabel(),
  3396.                 ], $subject);
  3397.                 $body $this->trans('notify_page_copy', [], 'cms'$targetLocale);
  3398.                 $body str_replace([
  3399.                     '((page_id))',
  3400.                     '((page_label))',
  3401.                     '((page_edit_url))',
  3402.                 ], [
  3403.                     $Page->getId(),
  3404.                     $Page->getLabel(),
  3405.                     $this->generateUrl('admin_page_edit', ['id' => $Page->getId()], UrlGenerator::ABSOLUTE_URL),
  3406.                 ], $body);
  3407.                 $mailer->setSubject($this->Settings->getLabel() . ': ' $subject)
  3408.                         ->setTo($notifyEmail)
  3409.                         ->setTwigBody('emails/notify.html.twig', [
  3410.                             'label' => '',
  3411.                             'message' => nl2br($body)
  3412.                         ])
  3413.                         ->setPlainBody(strip_tags($body));
  3414.                 $status $mailer->execute_forced();
  3415.             }
  3416.             header('Location: /bundles/cms/cache.php?url=' urlencode($this->generateUrl('admin_page', ['cloned' => $id])));
  3417.             exit;
  3418.             // Clear cache
  3419.             /*$this->clearcacheAction();
  3420.             return $this->redirect($this->generateUrl('admin_page_clone', ['id' => $id]) . '?cloned=1');*/
  3421.         }
  3422.         return $this->attributes(array(
  3423.             'Page' => $ActivePage,
  3424.             'post' => $_POST
  3425.         ));
  3426.     }
  3427.     public function parse$tpl$args = array() ){
  3428.         $args'Settings' ] = $this->Settings;
  3429.         $args'languages' ] = $this->getDoctrine()->getRepository('CmsBundle:Language')->findAll();
  3430.         if( !isset($args'bodyClass' ]) ) $args'bodyClass' ] = 'sub';
  3431.         return $this->render($tpl '.html.twig'$args);
  3432.     }
  3433.     public function notify(Page $Pagestring $message$subject ''){
  3434.         if($Page->getNotifyType() == 'telegram'){
  3435.             $ch curl_init();
  3436.             curl_setopt($chCURLOPT_URL,'https://api.telegram.org/' $Page->getNotifyTelegramBot() . '/sendMessage');
  3437.             curl_setopt($chCURLOPT_POST1);
  3438.             curl_setopt($chCURLOPT_POSTFIELDS,'chat_id=' $Page->getNotifyTelegramBotChatId() . '&text=' urlencode($message));
  3439.             curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  3440.             $server_output curl_exec ($ch);
  3441.             curl_close ($ch);
  3442.         }else{
  3443.             // Email
  3444.             if($Page->getNotifyEmail()){
  3445.                 $mailer = clone $this->mailer;
  3446.                 $mailer->init();
  3447.                 $mailer->setSubject($this->Settings->getLabel() . ': ' $subject)
  3448.                         ->setTo(explode(';'$Page->getNotifyEmail()))
  3449.                         ->setTwigBody('emails/notify.html.twig', [
  3450.                             'label' => '',
  3451.                             'message' => nl2br($message)
  3452.                         ])
  3453.                         ->setPlainBody($message);
  3454.                 $status $mailer->execute_forced();
  3455.             }
  3456.         }
  3457.     }
  3458.     /**
  3459.      * @Route("/admin/page/ajax/pageid/{id}", name="admin_page_ajax_pageid")
  3460.      */
  3461.     public function pageGetUrlAction(Request $request$id)
  3462.     {
  3463.         parent::init($request);
  3464.         $status false;
  3465.         $url '';
  3466.         $FirstPage null;
  3467.         $tmp_pages $this->getDoctrine()->getRepository('CmsBundle:Page')->findBy(array('page' => null'settings' => $this->Settings'enabled' => true), array('sort' => 'ASC'), 1);
  3468.         if(!empty($tmp_pages)){
  3469.             $FirstPage $tmp_pages[0];
  3470.         }
  3471.         if(!empty($id)) {
  3472.             $status true;
  3473.             
  3474.             if ($this->Settings->getForceHttps() || $request->isSecure()) {
  3475.                 $url 'https://';
  3476.             } else {
  3477.                 $url 'http://';
  3478.             }
  3479.             $em $this->getDoctrine()->getManager();
  3480.             $host $this->Settings->getHost();
  3481.             if (empty($host)) {
  3482.                 $host $em->getRepository('CmsBundle:Settings')->findOneBy([], ['id' => 'asc'])->getHost();
  3483.             }
  3484.             $lookupHost preg_replace('/:\d+/'''$request->getHttpHost());
  3485.             if(file_exists('../alias.json')){
  3486.                 $alias json_decode(file_get_contents('../alias.json'), true);
  3487.                 foreach($alias as $alias_parent => $aliasses){
  3488.                     if(array_key_exists($lookupHost$aliasses) || in_array($lookupHost$aliasses)){ 
  3489.                         $host $lookupHost;
  3490.                         if(!$request->isSecure()){
  3491.                             $url 'http://';
  3492.                         }
  3493.                     }
  3494.                 }
  3495.             }
  3496.             $url .= $host;
  3497.             $Page $em->getRepository('CmsBundle:Page')->find($id);
  3498.             if($FirstPage && $Page == $FirstPage){
  3499.                 $url .= $this->generateUrl('homepage');
  3500.                 $baseuri $Page->getSettings()->getBaseUri();
  3501.                 
  3502.                 $url rtrim($url'/') . $baseuri;
  3503.             }else{
  3504.                 $url .= $this->generateUrl('homepage') . $this->getDoctrine()->getRepository('CmsBundle:Page')->getSlugPathByPage($Page);
  3505.             }
  3506.         }
  3507.         return new JsonResponse([
  3508.             'status' => $status,
  3509.             'url' => $url,
  3510.         ]);
  3511.     }
  3512.     private function requestCriticalCss(Request $requestPage $Page) : void
  3513.     {
  3514.         parent::init($request);
  3515.         if ($Page->getEnabled() && $Page->getCritical())
  3516.         {
  3517.             $cssSuccess false;
  3518.             $foundOccasion false;
  3519.             //Check if page has a Occasionbundle linked and has default view
  3520.             if (isset($this->modRoutes['Occasions'])) {
  3521.                 foreach ($Page->getBlocks() as $wrapper) {
  3522.                     foreach ($wrapper->getBlocks() as $block) {
  3523.                         $bundleData json_decode($block->getBundleData(), true);
  3524.                         // contains
  3525.                         if (isset($bundleData['bundlename']) && $bundleData['bundlename'] == 'TrinityOccasionsBundle' && isset($bundleData['display']) && $bundleData['display'] == 'default') {
  3526.                             $foundOccasion true;
  3527.                         }
  3528.                     }
  3529.                 }
  3530.             }
  3531.             $criticalHost 'https://critical.beyonitdev.nl';
  3532.             if(!empty($_ENV['CRITICAL_HOST'])){
  3533.                 $criticalHost $_ENV['CRITICAL_HOST'];
  3534.             }
  3535.             try {
  3536.                 $cssSuccess false;
  3537.                 if(!empty($Page->getSlugKey())){
  3538.                     $pageSlug $this->generateUrl($Page->getSlugKey());
  3539.                     $remoteUrl        $request->headers->get('origin');
  3540.                     $criticalUrl    $request->headers->get('origin') . $pageSlug;
  3541.                     $pageId            $Page->getId();
  3542.                     $type            'page';
  3543.                     if ($foundOccasion) {
  3544.                         $occasion $this->em->getRepository('TrinityOccasionsBundle:Occasion')->findOneby([], ['id' => 'asc']);
  3545.                         $pageSlug $pageSlug '/' $occasion->getId() . '/' $occasion->getSlug();
  3546.                     }
  3547.                     $disabledhosts = [
  3548.                         '.local',
  3549.                         '.dev',
  3550.                     ];
  3551.                     foreach ($disabledhosts as $host) {
  3552.                         if (str_ends_with($remoteUrl$host)) {
  3553.                             return;
  3554.                         }
  3555.                     }
  3556.                     $postArray = [
  3557.                         'remoteUrl'        => $remoteUrl,
  3558.                         'criticalUrl'    => $criticalUrl,
  3559.                         'pageId'        => $pageId,
  3560.                         'type'          => $type,
  3561.                         'token'            => '!Uv7JHmrR*A9@sy._WzFr*7rqnrvkjR@',
  3562.                     ];
  3563.                     $ch curl_init();
  3564.                     curl_setopt($chCURLOPT_URL$criticalHost);
  3565.                     curl_setopt($chCURLOPT_POSTtrue);
  3566.                     curl_setopt($chCURLOPT_POSTFIELDS$postArray);
  3567.                     curl_setopt($chCURLOPT_FOLLOWLOCATIONtrue);
  3568.                     curl_setopt($chCURLOPT_RETURNTRANSFER1);
  3569.                     $data curl_exec($ch);
  3570.                     $info curl_getinfo($ch);
  3571.                     if (isset($info['http_code']) and $info['http_code'] == 200)
  3572.                     {
  3573.                         $data json_decode($datatrue);
  3574.                         if (isset($data['status']) && $data['status'] == 'true') {
  3575.                             $cssSuccess true;
  3576.                         }
  3577.                     }
  3578.                     curl_close($ch);
  3579.                     // reset critcal so the generator doesn't see it.
  3580.                     $Page->setCricitalCss(null); // Clear critical Css don't reset cricital
  3581.                 }
  3582.             } catch (Exception $ex) {
  3583.                 //dump('cacht');die();
  3584.             } finally {
  3585.                 $Syslog = new Log();
  3586.                 $Syslog->setUser($this->getUser());
  3587.                 $Syslog->setUsername($this->getUser()->getUsername());
  3588.                 $Syslog->setType('page');
  3589.                 $Syslog->setStatus('info');
  3590.                 $Syslog->setObjectId($Page->getId());
  3591.                 $Syslog->setSettings($this->Settings);
  3592.                 if ($cssSuccess) {
  3593.                     $Syslog->setAction('success');
  3594.                     $Syslog->setMessage('Pagina \'' $Page->getLabel() . '\' critical css aangevraagd.');
  3595.                 } else {
  3596.                     $Syslog->setAction('failed');
  3597.                     $Syslog->setMessage('Pagina \'' $Page->getLabel() . '\' critical css aanvraag mislukt.');
  3598.                 }
  3599.                 $this->em->persist($Syslog);
  3600.                 $this->em->flush();
  3601.             }
  3602.         }
  3603.     }
  3604.     /**
  3605.       * This function saves the generated critical so it can be used.
  3606.       *
  3607.       * @Route("/__submit_critical", name="page_submit_critical_css")
  3608.       *
  3609.       * @param Request $request
  3610.       * @return JsonResponse
  3611.       */
  3612.     public function criticalSubmitAction(Request $request) : JsonResponse
  3613.     {
  3614.         $status false;
  3615.         $message 'failed';
  3616.         try {
  3617.             $em $this->getDoctrine()->getManager();
  3618.             $itemId        $request->request->get('pageId');
  3619.             $content    $request->request->get('content');
  3620.             $token        $request->request->get('token');
  3621.             $type       $request->request->get('type');
  3622.             if (!empty($token) && $token == 'zAjrsTNpyMD8LtpZc_m!bbout@oqXcAs')
  3623.             {
  3624.                 if (!empty($content)) {
  3625.                     $Page $em->getRepository('CmsBundle:Page')->find($itemId);
  3626.                     if (!empty($Page)) {
  3627.                         $Page->setCricitalCss($content);
  3628.                         $Page->setCacheData(null); // Clear page cache, so page cache is regenerated with critical
  3629.                         $status true;
  3630.                         $message 'success';
  3631.                     }
  3632.                     if ($type == 'product') {
  3633.                         if (file_exists($projectDir '/templates/override/webshop/')) {
  3634.                             mkdir ($projectDir '/templates/override/webshop/');
  3635.                         }
  3636.                         //override webshop
  3637.                         $productDir $projectDir '/templates/override/webshop/product-critical.html.twig';
  3638.                         //file_put_contents($productDir, $content);
  3639.                     }
  3640.                     if ($type == 'category') {
  3641.                         if (file_exists($projectDir '/templates/override/webshop/')) {
  3642.                             mkdir ($projectDir '/templates/override/webshop/');
  3643.                         }
  3644.                         $productDir $projectDir '/templates/override/webshop/category-critical.html.twig';
  3645.                         //file_put_contents($productDir, $content);
  3646.                     }
  3647.                     if ($type == 'checkout') {
  3648.                         if (file_exists($projectDir '/templates/override/webshop/')) {
  3649.                             mkdir ($projectDir '/templates/override/webshop/');
  3650.                         }
  3651.                         $productDir $projectDir '/templates/webshop/checkout-critical.html.twig';
  3652.                         //file_put_contents($productDir, $content);
  3653.                     }
  3654.                 } else {
  3655.                     $message 'empty content';
  3656.                 }
  3657.             } else {
  3658.                 $message 'denied';
  3659.             }
  3660.         } catch (\Exception $ex) {
  3661.             $message 'exception: ' $ex->getMessage();
  3662.         }
  3663.         return new JsonResponse([
  3664.             'status' => $status,
  3665.             'message' => 'pagecontroller ' $message,
  3666.         ]);
  3667.     }
  3668. }