<?php
namespace App\Controller\Engine;
use App\Entity\Base3\UserFilter;
use App\Entity\LostFile;
use App\Entity\LostImage;
use App\Form\Base3\ReportFilters\LaydownReportFilterType;
use App\Form\PostType;
use App\Model\SystemControl;
use App\Repository\Base3\UserFilterRepository;
use App\Repository\LostFileRepository;
use App\Repository\SystemControlRepository;
use App\Repository\UserRepository;
use App\Service\AuthenticationService;
use App\Service\DefaultDateService;
use App\Service\LiformHelper;
use App\Service\TranslationHelper;
use Carbon\Carbon;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
// use Symfony\Component\HttpFoundation\Response;
class EngineController extends AbstractController
{
/**
* Returns the engine template
*
* @Route("/", name="homepage")
* @return Response
*/
// * @Route("/{engineRouting}", requirements={"engineRouting"="^(?!api|template|_(profiler|wdt)).*"}, name="engine_index")
// public function EngineAction($engineRouting): Response
public function EngineCasing(Request $request): Response
{
$language = $this->getUser()->getLanguage();
if (null !== $language) {
$request->getSession()->set('_locale', $language);
}
return $this->render('@engine/casing.html.twig');
}
/**
* @Route("/engine/twig/", name="engine_main", methods="GET", options={"expose"=true})
*/
public function EngineAction(): Response
{
return $this->render('@engine/casing/engine.html.twig');
}
/**
* @Route("/engine/twig/layout/{template}", name="engine_layout", methods="GET", options={"expose"=true})
*/
public function EngineLayout(Request $request, $template)
{
$ignitionSettings = $this->EngineIgnitionService($template);
return $this->render("@layout/$template.html.twig", $ignitionSettings);
}
/**
* @Route("/insight", name="insight_token", methods="GET", options={"expose"=true})
*/
public function Insight(Request $request)
{
// session on licence level
// three api tokens
$url = "https://panintelligence.base.website/";
$user = $this->getUser();
// workaround until we get more liscences
$username = $_ENV['PI_USER']; //Change this to the user you want to login as
// $username = $user->getUsername();
$password = $_ENV['PI_PASSWORD']; //Change this to user's password
$apiToken = "panMISDashboardWebServices/api/token/";
$httpClient = HttpClient::create();
// it makes an HTTP GET request to https://httpbin.org/get?token=...&name=...
$response = $httpClient->request('POST', $url.$apiToken, [
// these values are automatically encoded before including them in the URL
'query' => [
'username' => $username,
'password' => $password
// ,
// 'loginAs' => // set password as expired
],
]);
$xml = simplexml_load_string($response->getContent());
$token = (string)$xml->Token[0];
$response = new Response();
$response->setContent(json_encode([
'token'=>$token
]));
// $response->headers->set("Authorization", "bearer " . $token);
return $response;
}
/**
* @Route("/engine/twig/part/sidebar", name="engine_sidebar", methods="GET", options={"expose"=true})
* @param SystemControlRepository $systemControlRepo
* @param AuthenticationService $authentication
* @param DefaultDateService $dateService
* @return Response
*/
public function EngineSidebar(SystemControlRepository $systemControlRepo, AuthenticationService $authentication, DefaultDateService $dateService, TranslationHelper $translationHelper): Response
{
$menu1 = $systemControlRepo->findOneBy([
'slug' => SystemControl::MAIN_MENU_1,
]);
$menu = $menu1->getPj();
$menu = $translationHelper->translateKeyInArray($menu, 'name');
foreach ($menu as $key => $value) {
if(isset($menu[$key]['submenu'])){
$menu[$key]['submenu'] = $translationHelper->translateKeyInArray($menu[$key]['submenu'], 'name');
}
}
$menu = $translationHelper->translateKeyInNestedArray($menu, 'name');
$data = $dateService->defaultDateForNavigation($menu);
$navigationSetting = [
'menu' => $data ?? [],
'menutwo' => [], //$menu2->getPj() ?? [],
'menuthree' => [], //$menu3->getPj() ?? [],
'userroles' => $authentication->getUserRoleHierarchy($this->getUser()),
];
return $this->render("@layout/sidebar.html.twig", $navigationSetting);
}
/**
* @Route("/engine/twig/engine/login", name="engine_login_template", methods="GET", options={"expose"=true})
*/
public function EngineLogin(Request $request)
{
$sidebarSettings = $this->EngineSidebarService();
return $this->render('@engine/login/templates/login.html.twig');
}
/**
* @Route("/engine/twig/component/{component}/{template}", name="engine_component", methods="GET", options={"expose"=true})
*/
public function EngineComponent(Request $request, $component, $template)
{
return $this->render("@component/$component/$template.html.twig", [
]);
}
/**
* @Route("/engine/twig/part/{mode}/{template}", name="engine_part", methods="GET", options={"expose"=true})
*/
public function EnginePart(Request $request, $mode, $template)
{
$ignitionSettings = $this->EngineIgnitionService($template);
return $this->render("@part/$mode/templates/".$template.".html.twig", [
// 'form' => $form->createView(),
]);
}
/**
* @Route("/engine/twig/module/{mode}/{template}", name="engine_module", methods="GET", options={"expose"=true})
*/
public function EngineModule(Request $request, $mode, $template)
{
return $this->render("@module/$mode/templates/".$template.".html.twig", [
// 'form' => $form->createView(),
]);
}
/**
* @Route("/engine/twig/template/{mode}/{template}", name="engine_template", methods="GET", options={"expose"=true})
*/
public function EngineTemplate(Request $request, $mode, $template)
{
$options = $request->query->all();
$availableTabs = null;
if(array_key_exists('availableTabs', $options)) {
$availableTabs = $options['availableTabs'];
}
return $this->render($mode."/".$template.".html.twig", [
// 'form' => $form->createView(),
'availableTabs' => $availableTabs
]);
}
/**
* @Route("/engine/twig/filter/{mode}/{template}", name="engine_filters", options={"expose"=true})
*/
public function EngineFilters(Request $request, $mode, $template)
{ //
$user = $this->getUser()->getId();
$em = $this->getDoctrine()->getManager();
// $filters = $em->getRepository('App:Base3\UserFilter');
// $filterSet = $request->query->get('filterSet');
// // $savedFilters = $filters->findByRoute($user, $filterSet);
// $savedFilters = [];
// if($filterSet != '' || $filterSet != null){
// $conn = $em->getConnection();
// $sql = "SELECT *
// FROM b3_user_filter uf
// WHERE uf.user_id = $user
// AND uf.route = '$template'
// AND uf.description = '$filterSet'
// ";
// $stmt = $conn->prepare($sql);
// $stmt->execute();
// $res = $stmt->fetchAll();
// $savedFilters = json_decode($res[0]["filter_data"], true);
// }
// // $activeFilter = $filters->findOneByRoute($route, $user, $filterSet);
// $activeFilter = [];//$filters->findOneByRoute($route, $user, $filterSet);
// if($filterSet != '' || $filterSet != null){
// $conn = $em->getConnection();
// $sql = "SELECT *
// FROM b3_user_filter uf
// WHERE uf.user_id = $user
// AND uf.route = '$template'
// ";
// $stmt = $conn->prepare($sql);
// $stmt->execute();
// $res = $stmt->fetchAll();
// $activeFilter = $res; //json_decode($res[0], true);
// }
//$userFilter = new UserFilter();
//, $userFilter
$form = $this->createForm(LaydownReportFilterType::class);
$response = [
"form" => $form->createView(),
//"activeFilter" => $activeFilter,
//"savedFilters" => $savedFilters
];
// dump($response); die;
// die;
return $this->render("@module/".$mode."/templates/".$template.".html.twig", $response);
}
// const DAYS_BEFORE_START_DATE = 30;
const ASSET_SPACE = "\public\\";
// const ASSET_SPACE_TEMP = "\var\\";
// const ASSET_SPACE_TEMP = "\protected\\";
// const ASSET_SPACE_PATH = "\var\filestore\";
const ASSET_FOLDER = 'filestore\avatars\\';
/**
* @Route("/engine/serve-file", name="serve_files", options={"expose"=true})
*/
public function serveFile(LostFileRepository $lostFileRepo, UserRepository $userRepo, EntityManagerInterface $em, LiformHelper $liformHelper, Request $request)
{
$assetSpace = self::ASSET_SPACE;
$projectDir = $this->getParameter('kernel.project_dir');
$image_marker = $request->query->get('image_marker', null);
// If this is an integer, increment it by four
if (is_numeric($image_marker)) {
$lostImage = $lostImageRepo->find(intval($image_marker));
$assetFolder = $lostImage->getFolder();
$filename = str_replace('\\', '/', $lostImage->getName());
} // If $a_bool is a string, print it out
else {
$assetFolder = self::ASSET_FOLDER;
$filename = $image_marker;
}
$resolvedResourcePath = $projectDir.$assetSpace.$assetFolder.$filename;
// i.e Sending a file from the resources folder in /web
// in this example, the TextFile.txt needs to exist in the server
// This should return the file located in /mySymfonyProject/web/public-resources/TextFile.txt
// to being viewed in the Browser
return new BinaryFileResponse($resolvedResourcePath);
}
// public function processAvatarChange(Avatar $avatar, Request $request)
/**
* @Route("/upload_image", name="engine_upload_image", options={"expose"=true}, methods="GET|POST")
*/
public function uploadImage(EntityManagerInterface $em, Request $request)
{
// retrieve the file with the name given in the form.
$file = $request->files->get('file');
$status = array('status' => "success","fileUploaded" => false);
$originalName = $file->getClientOriginalName();
// If a file was uploaded
if (!is_null($file)) {
// generate a random name for the file but keep the extension
$filename = uniqid().".".$file->getClientOriginalExtension();
// https://stackoverflow.com/questions/12363657/the-concept-of-virtual-host-and-dns
$filesystem = new Filesystem();
$projectDir = $this->getParameter('kernel.project_dir');
// $instanceDir = isset($_ENV['INSTANCE_DIR']) ? $_ENV['INSTANCE_DIR'] : '/public/';
// try {
// $filesystem->mkdir($projectDir.$instanceDir.random_int(0, 1000));
// } catch (IOExceptionInterface $exception) {
// echo "An error occurred while creating your directory at ".$exception->getPath();
// }
$folder = 'filestore/';
$path = $projectDir.'/public/'.$folder;
// $path = $projectDir.$instanceDir.$folder;
if (!is_dir($path)) { // does the path exist
mkdir($path, 0700, true); //make the path with permission recursively
}
$file->move($path, $filename); // move the file to a path
// do some stuff here
$owner = $this->getUser();
$file = new LostImage;
$file->setName($filename);
$file->setOriginalName($originalName);
$file->setFolder($folder);
$file->setOwner($owner);
$file->setAlt($filename);
$file->setType('image');
$file->setAccess();
$em->persist($file);
$em->flush();
$status = [
'status' => "success",
"fileUploaded" => true,
"filepath" => $path.$filename,
"id" => $file->getId()
];
}
return new JsonResponse($status);
}
// public function processAvatarChange(Avatar $avatar, Request $request)
/**
* @Route("/upload_file", name="engine_upload_file", options={"expose"=true}, methods="GET|POST")
*/
public function uploadFile(TranslationHelper $translationHelper, EntityManagerInterface $em, Request $request)
{
// retrieve the file with the name given in the form.
$file = $request->files->get('file');
$options = $request->request->all();
// If a file was uploaded
if (!is_null($file)) {
$originalName = $file->getClientOriginalName();
$status = array('status' => "success","fileUploaded" => false);
// generate a random name for the file but keep the extension
$filename = uniqid().".".$file->getClientOriginalExtension();
// https://stackoverflow.com/questions/12363657/the-concept-of-virtual-host-and-dns
$filesystem = new Filesystem();
$projectDir = $this->getParameter('kernel.project_dir');
// try {
// $filesystem->mkdir($projectDir.'/public'.random_int(0, 1000));
// } catch (IOExceptionInterface $exception) {
// echo "An error occurred while creating your directory at ".$exception->getPath();
// }
$instanceDir = isset($_ENV['INSTANCE_DIR']) ? $_ENV['INSTANCE_DIR'] : '/var/';
try {
$filesystem->mkdir($projectDir.$instanceDir.random_int(0, 1000));
} catch (IOExceptionInterface $exception) {
echo "An error occurred while creating your directory at ".$exception->getPath();
}
$folder = 'filestore/';
// $path = $projectDir.'/protected/'.$folder;
$path = $projectDir.$instanceDir.$folder;
if (!is_dir($path)) { // does the path exist
mkdir($path, 0700, true); //make the path with permission recursively
}
$file->move($path, $filename); // move the file to a path
$ext = explode('.', $filename);
// dump($r[0]);
// dump($r[1]);
// dump(end($r));
// dd( 'here' );
$filetype = end($ext);
// $filetype = end(explode('.',$filename));
// dd($filetype);
// do some stuff here
$owner = $this->getUser();
$file = new LostFile;
$file->setName($filename);
$file->setOriginalName($originalName);
$file->setFolder($folder);
$file->setOwner($owner);
$file->setAlt($filename);
$file->setType($filetype);
$file->setAccess($options['permissions']);
// $file->setAccess(['blah']);
$em->persist($file);
$em->flush();
$status = [
'status' => "success",
"fileUploaded" => true,
"fileType" => $filetype,
"fileName" => $filename,
"originalName" => $originalName,
"filepath" => $path.$filename,
"id" => $file->getId()
];
} else {
$status = [ 'data' => $translationHelper->translateString('There was a server error, please contact support if this keeps happening.')];
}
return new JsonResponse($status);
}
private function EngineSidebarService()
{
$userObj = $this->getUser();
if ($userObj == null) {
$user = 'unknown';
$tier = 'unknown';
} else {
$user = $userObj->getUsername();
$tier = 'atari'; //$user->getTier();
}
switch ($tier) {
case 'unknown':
$menu = [];
break;
case 'atari':
$menu = [
[
'name'=> 'Dashboard',
'sref' => "base.engine",
'icon' => 'fal fa-fw fa-home'
],
[
'name'=> 'Activities',
'sref'=> 'base.engine.laydown',
'icon' => 'fal fa-fw fa-heartbeat'
],
[
'name'=> 'Budgets',
'sref' => "base.engine.budget",
'icon' => 'fal fa-fw fa-calculator'
],
[
'name'=> 'Activations',
'sref' => "base.engine.activation",
'icon' => 'fal fa-fw fa-list'
],
[
'name'=> 'Reports',
'sref' => "base.engine.roi_report",
'icon' => 'fal fa-fw fa-chart-line',
'submenu' => [
[
'name' => 'Return on Investment',
'sref' => "base.engine.roi_report",
'icon' => 'fal fa-fw fa-chart-line'
],
[
'name' => 'Range Review',
'sref' => "base.engine.rr_report",
'icon' => 'fal fa-fw fa-chart-bar'
]
]
],
];
break;
}
$menutwo = [
[
'name'=> 'Maintenance',
'sref'=> 'base.engine.maintenance',
'icon' => 'fal fa-fw fa-wrench'
],
];
$menuthree = [
[
'name'=> 'CRM',
'sref' => "base.engine.profile",
'icon' => 'fal fa-fw fa-users'
],
[
'name'=> 'Mail builder',
'sref' => "",
'icon' => 'fal fa-fw fa-envelope'
],
];
$navigationSetting = [
'menu' => $menu,
'menutwo' => $menutwo,
'menuthree' =>$menuthree ,
];
return $navigationSetting;
}
private function EngineIgnitionService($sparkplug)
{
$user = 'unknown';
if ($sparkplug === 'goalposts') {
$userObj= $this->getUser();
if ($userObj == null) {
$user = 'unknown';
$tier = 'unknown';
} else {
$user = $userObj->getUsername();
$tier = 'atari'; //$user->getTier();
}
$ignitionSettings = [
'username' => $user,
'session_salt' => 'baseSession'.random_int(0, 100)
];
} else {
$ignitionSettings = [
'username' => $user,
'session_salt' => 'baseSession'.random_int(0, 100)
];
}
return $ignitionSettings;
}
/**
* @Route("/api/ignition-switch",name="ignite", options={"expose"=true})
* @return Response
*/
public function IngitionSwitch()
{
$listGroup = '[
{"endpoint":"base.engine.campaign.list","amount":10,"text":"Campaign", "desc":"Manage your campaigns."}
]';
// $userObj= $this->getUser();
// $user = $userObj->getUsername();
$userRole = preg_replace('/\s+/', '', $listGroup);
$response = [
'code' => 200,
'action' => $userRole
];
return new JsonResponse($response);
}
/**
* @Route("/api/media_channel_data",name="api_media_channel_data", options={"expose"=true})
* @return Response
*/
public function mediaChannelData()
{
$json = $this->getJsonFixture('media_channel_data');
$serializer = $this->container->get('serializer');
$serializedResponse = $serializer->serialize($json, 'json');
$response = new Response($serializedResponse);
$response->headers->set('Content-Type', 'application/json');
return $response;
// $response = new JsonResponse();
// $response->setData($results);
// return $response;
// return new JsonResponse($response);
}
/**
*/
private function getJsonFixture($file) // another blooming time sink
{
// $file = 'campaign_touchpoints'; //
$webPath = $this->getParameter('kernel.project_dir');
$fixture = file_get_contents($webPath.'/fixture/'+$file+'.json');
return $fixture;
// $serializer = $this->container->get('serializer');
// $serializedResponse = $serializer->serialize($response, 'json');
// $response = new Response($serializedResponse);
// $response->headers->set('Content-Type', 'application/json');
// return $response;
}
}