src/Controller/Engine/EngineController.php line 44

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Engine;
  3. use App\Entity\Base3\UserFilter;
  4. use App\Entity\LostFile;
  5. use App\Entity\LostImage;
  6. use App\Form\Base3\ReportFilters\LaydownReportFilterType;
  7. use App\Form\PostType;
  8. use App\Model\SystemControl;
  9. use App\Repository\Base3\UserFilterRepository;
  10. use App\Repository\LostFileRepository;
  11. use App\Repository\SystemControlRepository;
  12. use App\Repository\UserRepository;
  13. use App\Service\AuthenticationService;
  14. use App\Service\DefaultDateService;
  15. use App\Service\LiformHelper;
  16. use App\Service\TranslationHelper;
  17. use Carbon\Carbon;
  18. use Doctrine\ORM\EntityManagerInterface;
  19. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  20. use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
  21. use Symfony\Component\Filesystem\Filesystem;
  22. use Symfony\Component\HttpClient\HttpClient;
  23. use Symfony\Component\HttpFoundation\JsonResponse;
  24. use Symfony\Component\HttpFoundation\Request;
  25. use Symfony\Component\HttpFoundation\Response;
  26. use Symfony\Component\Routing\Annotation\Route;
  27. // use Symfony\Component\HttpFoundation\Response;
  28. class EngineController extends AbstractController
  29. {
  30.     /**
  31.      * Returns the engine template
  32.      *
  33.      * @Route("/", name="homepage")
  34.      * @return Response
  35.      */
  36.     // * @Route("/{engineRouting}", requirements={"engineRouting"="^(?!api|template|_(profiler|wdt)).*"}, name="engine_index")
  37.     // public function EngineAction($engineRouting): Response
  38.     public function EngineCasing(Request $request): Response
  39.     {
  40.         $language $this->getUser()->getLanguage();
  41.         if (null !== $language) {
  42.             $request->getSession()->set('_locale'$language);
  43.         }
  44.         return $this->render('@engine/casing.html.twig');
  45.     }
  46.     /**
  47.      * @Route("/engine/twig/", name="engine_main", methods="GET", options={"expose"=true})
  48.      */
  49.     public function EngineAction(): Response
  50.     {
  51.         return $this->render('@engine/casing/engine.html.twig');
  52.     }
  53.     /**
  54.      * @Route("/engine/twig/layout/{template}", name="engine_layout", methods="GET", options={"expose"=true})
  55.      */
  56.     public function EngineLayout(Request $request$template)
  57.     {
  58.         $ignitionSettings $this->EngineIgnitionService($template);
  59.         return $this->render("@layout/$template.html.twig"$ignitionSettings);
  60.     }
  61.     /**
  62.      * @Route("/insight", name="insight_token", methods="GET", options={"expose"=true})
  63.      */
  64.     public function Insight(Request $request)
  65.     {
  66.         // session on licence level
  67.         // three api tokens
  68.         $url "https://panintelligence.base.website/";
  69.         $user $this->getUser();
  70.         // workaround until we get more liscences
  71.         $username $_ENV['PI_USER']; //Change this to the user you want to login as
  72.         // $username = $user->getUsername();
  73.         $password $_ENV['PI_PASSWORD']; //Change this to user's password
  74.         $apiToken "panMISDashboardWebServices/api/token/";
  75.         $httpClient HttpClient::create();
  76.         // it makes an HTTP GET request to https://httpbin.org/get?token=...&name=...
  77.         $response $httpClient->request('POST'$url.$apiToken, [
  78.             // these values are automatically encoded before including them in the URL
  79.             'query' => [
  80.                 'username' => $username,
  81.                 'password' => $password
  82.                 // ,
  83.                 // 'loginAs' => // set password as expired
  84.             ],
  85.         ]);
  86.         $xml simplexml_load_string($response->getContent());
  87.         $token = (string)$xml->Token[0];
  88.         $response = new Response();
  89.         $response->setContent(json_encode([
  90.             'token'=>$token
  91.         ]));
  92.         // $response->headers->set("Authorization", "bearer " . $token);
  93.         return $response;
  94.     }
  95.     /**
  96.      * @Route("/engine/twig/part/sidebar", name="engine_sidebar", methods="GET", options={"expose"=true})
  97.      * @param SystemControlRepository $systemControlRepo
  98.      * @param AuthenticationService $authentication
  99.      * @param DefaultDateService $dateService
  100.      * @return Response
  101.      */
  102.     public function EngineSidebar(SystemControlRepository $systemControlRepoAuthenticationService $authenticationDefaultDateService $dateServiceTranslationHelper $translationHelper): Response
  103.     {
  104.         $menu1 $systemControlRepo->findOneBy([
  105.             'slug' => SystemControl::MAIN_MENU_1,
  106.         ]);
  107.         $menu $menu1->getPj();
  108.         $menu $translationHelper->translateKeyInArray($menu'name');
  109.         foreach ($menu as $key => $value) {
  110.             if(isset($menu[$key]['submenu'])){
  111.                 $menu[$key]['submenu'] = $translationHelper->translateKeyInArray($menu[$key]['submenu'], 'name');
  112.             }
  113.         }
  114.         $menu $translationHelper->translateKeyInNestedArray($menu'name');
  115.         $data $dateService->defaultDateForNavigation($menu);
  116.         $navigationSetting = [
  117.             'menu' => $data ?? [],
  118.             'menutwo' => [], //$menu2->getPj() ?? [],
  119.             'menuthree' => [], //$menu3->getPj() ?? [],
  120.             'userroles' => $authentication->getUserRoleHierarchy($this->getUser()),
  121.         ];
  122.         return $this->render("@layout/sidebar.html.twig"$navigationSetting);
  123.     }
  124.     /**
  125.      * @Route("/engine/twig/engine/login", name="engine_login_template", methods="GET", options={"expose"=true})
  126.      */
  127.     public function EngineLogin(Request $request)
  128.     {
  129.         $sidebarSettings $this->EngineSidebarService();
  130.         return $this->render('@engine/login/templates/login.html.twig');
  131.     }
  132.     /**
  133.      * @Route("/engine/twig/component/{component}/{template}", name="engine_component", methods="GET", options={"expose"=true})
  134.      */
  135.     public function EngineComponent(Request $request$component$template)
  136.     {
  137.         return $this->render("@component/$component/$template.html.twig", [
  138.         ]);
  139.     }
  140.     /**
  141.      * @Route("/engine/twig/part/{mode}/{template}", name="engine_part", methods="GET", options={"expose"=true})
  142.      */
  143.     public function EnginePart(Request $request$mode$template)
  144.     {
  145.         $ignitionSettings $this->EngineIgnitionService($template);
  146.         return $this->render("@part/$mode/templates/".$template.".html.twig", [
  147.             // 'form' => $form->createView(),
  148.         ]);
  149.     }
  150.     /**
  151.      * @Route("/engine/twig/module/{mode}/{template}", name="engine_module", methods="GET", options={"expose"=true})
  152.      */
  153.     public function EngineModule(Request $request$mode$template)
  154.     {
  155.         return $this->render("@module/$mode/templates/".$template.".html.twig", [
  156.             // 'form' => $form->createView(),
  157.         ]);
  158.     }
  159.     /**
  160.      * @Route("/engine/twig/template/{mode}/{template}", name="engine_template", methods="GET", options={"expose"=true})
  161.      */
  162.     public function EngineTemplate(Request $request$mode$template)
  163.     {
  164.         $options $request->query->all();
  165.         $availableTabs null;
  166.         if(array_key_exists('availableTabs'$options)) {
  167.             $availableTabs $options['availableTabs'];
  168.         }
  169.         return $this->render($mode."/".$template.".html.twig", [
  170.             // 'form' => $form->createView(),
  171.             'availableTabs' => $availableTabs
  172.         ]);
  173.     }
  174.     /**
  175.      * @Route("/engine/twig/filter/{mode}/{template}", name="engine_filters", options={"expose"=true})
  176.      */
  177.     public function EngineFilters(Request $request$mode$template)
  178.     { //
  179.         $user $this->getUser()->getId();
  180.         $em $this->getDoctrine()->getManager();
  181.         // $filters = $em->getRepository('App:Base3\UserFilter');
  182.         // $filterSet = $request->query->get('filterSet');
  183.         // // $savedFilters = $filters->findByRoute($user, $filterSet);
  184.         // $savedFilters = [];
  185.         // if($filterSet != '' || $filterSet != null){
  186.         //     $conn = $em->getConnection();
  187.         //     $sql = "SELECT *
  188.         //             FROM b3_user_filter uf
  189.         //             WHERE uf.user_id = $user
  190.         //             AND uf.route = '$template'
  191.         //             AND uf.description = '$filterSet'
  192.         //         ";
  193.         //     $stmt = $conn->prepare($sql);
  194.         //     $stmt->execute();
  195.         //     $res = $stmt->fetchAll();
  196.         //     $savedFilters = json_decode($res[0]["filter_data"], true);
  197.         // }
  198.         // // $activeFilter = $filters->findOneByRoute($route, $user, $filterSet);
  199.         // $activeFilter = [];//$filters->findOneByRoute($route, $user, $filterSet);
  200.         // if($filterSet != '' || $filterSet != null){
  201.         //     $conn = $em->getConnection();
  202.         //     $sql = "SELECT *
  203.         //             FROM b3_user_filter uf
  204.         //             WHERE uf.user_id = $user
  205.         //             AND uf.route = '$template'
  206.         //         ";
  207.         //     $stmt = $conn->prepare($sql);
  208.         //     $stmt->execute();
  209.         //     $res = $stmt->fetchAll();
  210.         //     $activeFilter = $res; //json_decode($res[0], true);
  211.         // }
  212.         //$userFilter = new UserFilter();
  213.         //, $userFilter
  214.         $form $this->createForm(LaydownReportFilterType::class);
  215.         $response = [
  216.             "form" => $form->createView(),
  217.             //"activeFilter" => $activeFilter,
  218.             //"savedFilters" => $savedFilters
  219.         ];
  220.         // dump($response); die;
  221.         // die;
  222.         return $this->render("@module/".$mode."/templates/".$template.".html.twig"$response);
  223.     }
  224.     // const DAYS_BEFORE_START_DATE = 30;
  225.     const ASSET_SPACE "\public\\";
  226.     // const ASSET_SPACE_TEMP = "\var\\"; 
  227.     // const ASSET_SPACE_TEMP = "\protected\\"; 
  228.     // const ASSET_SPACE_PATH = "\var\filestore\"; 
  229.     const ASSET_FOLDER 'filestore\avatars\\';
  230.     /**
  231.      * @Route("/engine/serve-file", name="serve_files", options={"expose"=true})
  232.      */
  233.     public function serveFile(LostFileRepository $lostFileRepoUserRepository $userRepoEntityManagerInterface $emLiformHelper $liformHelperRequest $request)
  234.     {
  235.         $assetSpace self::ASSET_SPACE;
  236.         $projectDir $this->getParameter('kernel.project_dir');
  237.         $image_marker $request->query->get('image_marker'null);
  238.         // If this is an integer, increment it by four
  239.         if (is_numeric($image_marker)) {
  240.             $lostImage $lostImageRepo->find(intval($image_marker));
  241.             $assetFolder $lostImage->getFolder();
  242.             $filename str_replace('\\''/'$lostImage->getName());
  243.         } // If $a_bool is a string, print it out
  244.         else {
  245.             $assetFolder self::ASSET_FOLDER;
  246.             $filename $image_marker;
  247.         }
  248.         $resolvedResourcePath $projectDir.$assetSpace.$assetFolder.$filename;
  249.         // i.e Sending a file from the resources folder in /web
  250.         // in this example, the TextFile.txt needs to exist in the server
  251.         // This should return the file located in /mySymfonyProject/web/public-resources/TextFile.txt
  252.         // to being viewed in the Browser
  253.         return new BinaryFileResponse($resolvedResourcePath);
  254.     }
  255.     // public function processAvatarChange(Avatar $avatar, Request $request)
  256.     /**
  257.      * @Route("/upload_image", name="engine_upload_image", options={"expose"=true}, methods="GET|POST")
  258.      */
  259.     public function uploadImage(EntityManagerInterface $emRequest $request)
  260.     {
  261.         // retrieve the file with the name given in the form.
  262.         $file $request->files->get('file');
  263.         $status = array('status' => "success","fileUploaded" => false);
  264.         $originalName $file->getClientOriginalName();
  265.         // If a file was uploaded
  266.         if (!is_null($file)) {
  267.             // generate a random name for the file but keep the extension
  268.             $filename uniqid().".".$file->getClientOriginalExtension();
  269.             // https://stackoverflow.com/questions/12363657/the-concept-of-virtual-host-and-dns
  270.             $filesystem = new Filesystem();
  271.             $projectDir $this->getParameter('kernel.project_dir');
  272.             // $instanceDir = isset($_ENV['INSTANCE_DIR']) ? $_ENV['INSTANCE_DIR'] : '/public/';
  273.             // try {
  274.             //     $filesystem->mkdir($projectDir.$instanceDir.random_int(0, 1000));
  275.             // } catch (IOExceptionInterface $exception) {
  276.             //     echo "An error occurred while creating your directory at ".$exception->getPath();
  277.             // }
  278.             $folder 'filestore/';
  279.             $path $projectDir.'/public/'.$folder;
  280.             // $path = $projectDir.$instanceDir.$folder;
  281.             if (!is_dir($path)) { // does the path exist
  282.                 mkdir($path0700true); //make the path with permission recursively
  283.             }
  284.             $file->move($path$filename); // move the file to a path
  285.             // do some stuff here 
  286.             $owner $this->getUser();
  287.             $file = new LostImage;
  288.             $file->setName($filename);
  289.             $file->setOriginalName($originalName);
  290.             $file->setFolder($folder);
  291.             $file->setOwner($owner);
  292.             $file->setAlt($filename);
  293.             $file->setType('image');
  294.             $file->setAccess();
  295.             $em->persist($file);
  296.             $em->flush();
  297.             $status = [
  298.                 'status' => "success",
  299.                 "fileUploaded" => true,
  300.                 "filepath" => $path.$filename,
  301.                 "id" => $file->getId()
  302.             ];
  303.         }
  304.         return new JsonResponse($status);
  305.     }
  306.     // public function processAvatarChange(Avatar $avatar, Request $request)
  307.     /**
  308.      * @Route("/upload_file", name="engine_upload_file", options={"expose"=true}, methods="GET|POST")
  309.      */
  310.     public function uploadFile(TranslationHelper $translationHelperEntityManagerInterface $emRequest $request)
  311.     {
  312.         // retrieve the file with the name given in the form.
  313.         $file $request->files->get('file');
  314.         $options $request->request->all();
  315.         // If a file was uploaded
  316.         if (!is_null($file)) {
  317.             $originalName $file->getClientOriginalName();
  318.             $status = array('status' => "success","fileUploaded" => false);
  319.             // generate a random name for the file but keep the extension
  320.             $filename uniqid().".".$file->getClientOriginalExtension();
  321.             // https://stackoverflow.com/questions/12363657/the-concept-of-virtual-host-and-dns
  322.             $filesystem = new Filesystem();
  323.             $projectDir $this->getParameter('kernel.project_dir');
  324.             // try {
  325.             //     $filesystem->mkdir($projectDir.'/public'.random_int(0, 1000));
  326.             // } catch (IOExceptionInterface $exception) {
  327.             //     echo "An error occurred while creating your directory at ".$exception->getPath();
  328.             // }
  329.             $instanceDir = isset($_ENV['INSTANCE_DIR']) ? $_ENV['INSTANCE_DIR'] : '/var/';
  330.             try {
  331.                 $filesystem->mkdir($projectDir.$instanceDir.random_int(01000));
  332.             } catch (IOExceptionInterface $exception) {
  333.                 echo "An error occurred while creating your directory at ".$exception->getPath();
  334.             }
  335.             $folder 'filestore/';
  336.             // $path = $projectDir.'/protected/'.$folder;
  337.             $path $projectDir.$instanceDir.$folder;
  338.             if (!is_dir($path)) { // does the path exist
  339.                 mkdir($path0700true); //make the path with permission recursively
  340.             }
  341.             $file->move($path$filename); // move the file to a path
  342.             $ext explode('.'$filename);
  343.             // dump($r[0]); 
  344.             // dump($r[1]); 
  345.             // dump(end($r)); 
  346.             // dd( 'here' );
  347.             $filetype end($ext);
  348.             // $filetype = end(explode('.',$filename));
  349.             // dd($filetype);
  350.             // do some stuff here 
  351.             $owner $this->getUser();
  352.             $file = new LostFile;
  353.             $file->setName($filename);
  354.             $file->setOriginalName($originalName);
  355.             $file->setFolder($folder);
  356.             $file->setOwner($owner);
  357.             $file->setAlt($filename);
  358.             $file->setType($filetype);
  359.             $file->setAccess($options['permissions']);
  360.             // $file->setAccess(['blah']);
  361.             $em->persist($file);
  362.             $em->flush();
  363.             $status = [
  364.                 'status' => "success",
  365.                 "fileUploaded" => true,
  366.                 "fileType" => $filetype,
  367.                 "fileName" => $filename,
  368.                 "originalName" => $originalName,
  369.                 "filepath" => $path.$filename,
  370.                 "id" => $file->getId()
  371.             ];
  372.         } else {
  373.             $status = [ 'data' => $translationHelper->translateString('There was a server error, please contact support if this keeps happening.')];
  374.         }
  375.         return new JsonResponse($status);
  376.     }
  377.     private function EngineSidebarService()
  378.     {
  379.         $userObj $this->getUser();
  380.         if ($userObj == null) {
  381.             $user 'unknown';
  382.             $tier 'unknown';
  383.         } else {
  384.             $user $userObj->getUsername();
  385.             $tier 'atari'//$user->getTier();
  386.         }
  387.         switch ($tier) {
  388.             case 'unknown':
  389.                 $menu = [];
  390.                 break;
  391.             case 'atari':
  392.                 $menu = [
  393.                     [
  394.                         'name'=> 'Dashboard',
  395.                         'sref' => "base.engine",
  396.                         'icon' => 'fal fa-fw fa-home'
  397.                     ],
  398.                     [
  399.                         'name'=> 'Activities',
  400.                         'sref'=> 'base.engine.laydown',
  401.                         'icon' => 'fal fa-fw fa-heartbeat'
  402.                     ],
  403.                     [
  404.                         'name'=> 'Budgets',
  405.                         'sref' => "base.engine.budget",
  406.                         'icon' => 'fal fa-fw fa-calculator'
  407.                     ],
  408.                     [
  409.                         'name'=> 'Activations',
  410.                         'sref' => "base.engine.activation",
  411.                         'icon' => 'fal fa-fw fa-list'
  412.                     ],
  413.                     [
  414.                         'name'=> 'Reports',
  415.                         'sref' => "base.engine.roi_report",
  416.                         'icon' => 'fal fa-fw fa-chart-line',
  417.                         'submenu' => [
  418.                             [
  419.                                 'name' => 'Return on Investment',
  420.                                 'sref' => "base.engine.roi_report",
  421.                                 'icon' => 'fal fa-fw fa-chart-line'
  422.                             ],
  423.                             [
  424.                                 'name' => 'Range Review',
  425.                                 'sref' => "base.engine.rr_report",
  426.                                 'icon' => 'fal fa-fw fa-chart-bar'
  427.                             ]
  428.                         ]
  429.                     ],
  430.                 ];
  431.                 break;
  432.         }
  433.         $menutwo = [
  434.             [
  435.                 'name'=> 'Maintenance',
  436.                 'sref'=> 'base.engine.maintenance',
  437.                 'icon' => 'fal fa-fw fa-wrench'
  438.             ],
  439.         ];
  440.         $menuthree = [
  441.             [
  442.                 'name'=> 'CRM',
  443.                 'sref' => "base.engine.profile",
  444.                 'icon' => 'fal fa-fw fa-users'
  445.             ],
  446.             [
  447.                 'name'=> 'Mail builder',
  448.                 'sref' => "",
  449.                 'icon' => 'fal fa-fw fa-envelope'
  450.             ],
  451.         ];
  452.         $navigationSetting = [
  453.             'menu' => $menu,
  454.             'menutwo' => $menutwo,
  455.             'menuthree' =>$menuthree ,
  456.         ];
  457.         return $navigationSetting;
  458.     }
  459.     private function EngineIgnitionService($sparkplug)
  460.     {
  461.         $user 'unknown';
  462.         if ($sparkplug === 'goalposts') {
  463.             $userObj$this->getUser();
  464.             if ($userObj == null) {
  465.                 $user 'unknown';
  466.                 $tier 'unknown';
  467.             } else {
  468.                 $user $userObj->getUsername();
  469.                 $tier 'atari'//$user->getTier();
  470.             }
  471.             $ignitionSettings = [
  472.                 'username' => $user,
  473.                 'session_salt' => 'baseSession'.random_int(0100)
  474.             ];
  475.         } else {
  476.             $ignitionSettings = [
  477.                 'username' => $user,
  478.                 'session_salt' => 'baseSession'.random_int(0100)
  479.             ];
  480.         }
  481.         return $ignitionSettings;
  482.     }
  483.     /**
  484.      * @Route("/api/ignition-switch",name="ignite", options={"expose"=true})
  485.      * @return Response
  486.      */
  487.     public function IngitionSwitch()
  488.     {
  489.         $listGroup '[
  490.                 {"endpoint":"base.engine.campaign.list","amount":10,"text":"Campaign",     "desc":"Manage your campaigns."}
  491.             ]';
  492.         // $userObj= $this->getUser();
  493.         // $user = $userObj->getUsername();
  494.         $userRole preg_replace('/\s+/'''$listGroup);
  495.         $response = [
  496.             'code' => 200,
  497.             'action' => $userRole
  498.         ];
  499.         return new JsonResponse($response);
  500.     }
  501.     /**
  502.      * @Route("/api/media_channel_data",name="api_media_channel_data", options={"expose"=true})
  503.      * @return Response
  504.      */
  505.     public function mediaChannelData()
  506.     {
  507.         $json $this->getJsonFixture('media_channel_data');
  508.         $serializer $this->container->get('serializer');
  509.         $serializedResponse $serializer->serialize($json'json');
  510.         $response = new Response($serializedResponse);
  511.         $response->headers->set('Content-Type''application/json');
  512.         return $response;
  513.         //  $response = new JsonResponse();
  514.         // $response->setData($results);
  515.         // return $response;
  516.         // return new JsonResponse($response);
  517.     }
  518.     /**
  519.      */
  520.     private function getJsonFixture($file// another blooming time sink
  521.     {
  522.         // $file = 'campaign_touchpoints'; //
  523.         $webPath =  $this->getParameter('kernel.project_dir');
  524.         $fixture file_get_contents($webPath.'/fixture/'+$file+'.json');
  525.         return $fixture;
  526.         // $serializer = $this->container->get('serializer');
  527.         // $serializedResponse = $serializer->serialize($response, 'json');
  528.         // $response = new Response($serializedResponse);
  529.         // $response->headers->set('Content-Type', 'application/json');
  530.         // return $response;
  531.     }
  532. }