<?php
namespace App\Controller;
use App\Base\ControllerBase;
use App\Entity\LicenseOrder;
use App\Entity\User;
use App\Entity\Company;
use App\Entity\Account;
use App\Entity\Driver;
use App\Entity\Vehicle;
use App\Entity\Trailer;
use App\Entity\Document;
use App\Entity\Setting;
use App\Entity\Link;
use App\Entity\BroadcastMessage; //COM-469
use App\Entity\SystemTip; // COM-695
use App\Entity\SystemTipLogEntry; // COM-695
use App\Services\TimeCalculator;
use App\Services\FormsHelper;
use App\Services\EmailNotifier;
use App\Services\RoutingHelper;
use App\Services\DocumentBuilder;
use App\Services\ActivityGraph;
use App\Type\UserRoleEnum;
use App\Type\DocumentTypeEnum;
use App\Type\CompanyConfigStatusTypeEnum;
use App\Type\CompanyAdminTypeEnum; // COM-479
use App\Type\BalanceTypeEnum;
use App\Type\BroadcastMessageReactionEnum; //COM-469
use App\Type\SystemTipStatusEnum; // COM-695
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Serializer\Serializer;
#use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\HttpFoundation\Session\Storage\SessionStorageInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Psr\Log\LoggerInterface;
use Sinergi\BrowserDetector\Browser;
class MainController extends ControllerBase
{
// ******************************************
// HOME & LOGIN
// ******************************************
/**
* @Route("/", name="b_home")
*/
public function home(Request $request)
{
$thisUserType = ($this->getUser()==null) ? null : $this->getUser()->getRolesUnconverted();
//dd('home thisUserType', $thisUserType);
return $this->redirectToRoute(RoutingHelper::getDefaultRoute($thisUserType));
}
// login route must correspond to security.yaml's firewalls/XXX/form_login config
/**
* @Route("/login-check", name="b_login_check")
*/
public function login_check(Request $request)
{
$tokenProvider = $this->container->get('security.csrf.token_manager');
$token = $tokenProvider->getToken('authenticate')->getValue();
//dump('tokenProvider', $tokenProvider);
//dump('token', $token);
$result = [];
return new Response($this->jsonEncoder(array(
's' => true,
't' => $token,
)));
}
// login route must correspond to security.yaml's firewalls/XXX/form_login config
/**
* @Route("/login", name="b_login")
*/
public function login(Request $request, AuthenticationUtils $authUtils)
{
//dump($this);
//dump($request);
//dump($authUtils);
//die();
////$this->handlePageOpen($request, 'general');
////$userRepository = $this->getDoctrine()->getRepository(User::class);
////$user = $userRepository->find(1);
//if ($user) echo $user->get_first_name();
$this->setLanguageAndLocale($request);
echo "<!-- ";
//$this->session->set('language', null);
//dump($this->session->get('language'));
dump('_SERVER', $_SERVER);
echo " -->";
// NB: when the user submits the form, the security system automatically handles the form submission
// JJM: if logged in already, redirect somewhere
// $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
// get the login error if there is one
$error = $authUtils->getLastAuthenticationError();
//dump($error);
//if ($error!=null && get_class($error)=='BadCredentialsException') dump($error->getMessage());
// last username entered by the user
$lastUsername = $authUtils->getLastUsername();
//echo "error=[$error], lastUsername=[$lastUsername]<br>"; //die();
$response = new Response();
$initialMessage = '';
$initialMessageType = 'info';
// get msgs from bag
if ($error==null && $initialMessage=='') {
foreach ($this->session->getFlashBag()->get('error', array()) as $message) {
$initialMessage = "showMsg('$message', false);";
$initialMessageType = 'error';
break;
}
}
if ($error==null && $initialMessage=='') {
foreach ($this->session->getFlashBag()->get('success', array()) as $message) {
$initialMessage = "showMsg('$message', true);";
$initialMessageType = 'success';
break;
}
}
// browser check, if not done yet
/*if ($error==false && $initialMessage=='') {
if ($request->cookies->get('ACE_browser_check')!='done') {
$browser = new Browser();
//dump($browser->getName());
if ($browser->getName() === Browser::IE) { //IE
$initialMessage = "showMsg('".$this->translator->trans('message.badBrowser', array(), 'general')."', 'info');";
$response->headers->setCookie(
new Cookie( 'ACE_browser_check', 'done', time() + (10 * 365 * 24 * 3600) )
);
}
}
}*/
/* // tell login page to show the pwd reminder form
$showPwdResetByDefault = false;
if ($this->session->get('login-page-referrer')!==null && $this->session->get('login-page-referrer')=='b_forgotPwd') {
$showPwdResetByDefault = true;
$this->session->remove('login-page-referrer');
} */
//dd($_COOKIE);
// COM-508
$response->headers->clearCookie('consumption-waybill', '/', null);
$systemInfo = $_SERVER['APP_SYSTEM_ID'];
if (0) {
if (0) {
$_SERVER['DATABASE_URL'] = '';
$_SERVER['szamlazz_hu_api'] = '';
$_SERVER['otp_simple_api_key'] = '';
dump('_SERVER', $_SERVER);
}
$varsToLog = [
'HTTP_HOST',
'HTTP_REFERER',
'HTTP_SEC_CH_UA_PLATFORM',
'HTTP_USER_AGENT',
'REDIRECT_SSL_TLS_SNI',
'REMOTE_ADDR',
'REMOTE_PORT',
'REQUEST_URI',
'SERVER_ADDR',
'SERVER_NAME',
'SERVER_PORT',
'SSL_TLS_SNI',
];
//$systemInfo .= "<br>____________";
foreach($varsToLog as $var) {
$systemInfo .= "<br>".$var.": ".($_SERVER[$var] ?? '-null-');
}
}
return $this->render('backend/login.html.twig', array(
'last_username' => $lastUsername,
'error' => $error,
'page_title' => $this->translator->trans('application.name', array(), 'general').' - '.
$this->translator->trans('page.title', array(), 'login'),
'initialMessage' => $initialMessage,
'initialMessageType' => $initialMessageType,
'currentLanguage' => $this->currentLanguage,
'systemInfo' => $systemInfo,
//'emailsAllowed' => $emailsAllowed,
//'showPwdResetByDefault' => $showPwdResetByDefault,
), $response);
}
/** COM-754
* @Route("/log-out", name="b_log_out")
*/
public function logout(Request $request)
{
$timeout = $request->query->get('timeout');
//dump('timeout', $timeout);
//dd();
$user = $this->getUser();
if ($user!==null) {
$user->__setDateTime('lastLogoutAt', 'now', true); //$this->timeCalc->currentDateTime);
if ($timeout==1) {
$user->__set('lastLogoutType', User::LOGOUT_TYPE_AUTOMATIC);
} else {
$user->__set('lastLogoutType', User::LOGOUT_TYPE_MANUAL);
}
$rc = $user->save( $this->getDoctrine()->getManager(), false );
if (!$rc) {
die('error updating user');
}
}
//dd('LOG OUT');
return $this->redirectToRoute('b_logout');
}
// ******************************************
// GENERAL ACTIONS (& CONFIG POPUP)
// ******************************************
/**
* @Route("/general/action", name="general.action", methods={"POST"})
*/
public function general_action(Request $request, DocumentBuilder $documentBuilder)
{
$result = $this->getDefaultAjaxReturnRec();
$returnData = array();
$em = $this->getDoctrine()->getManager();
//dump('request: '.$request);
$type = $request->request->get('type');
$step = $request->request->get('step');
$data = $request->request->get('data');
$companyId = $request->request->get('companyId') ?? null;
//dump('type: '.$type);
//dump('data', $data);
//dump('step', $step);
if ($step!==null) $step = intval($step);
$action = '';
if ($type=='togglePlayPause') {
$action = 'modeChange';
} else if ($type=='acceptTerms') {
$action = 'acceptTerms';
} else if ($type=='keepAlive') {
$action = 'keepAlive';
}
// company config steps
$CONFIG_STEPS = [
'company' => 0,
'tofu' => 1,
'contract' => 2,
'gdpr' => 3,
'cookies' => 4,
'licenseType' => 5,
'settings' => 6,
'finish' => 7,
];
// set up any parms for handleControllerAction() call below
$parms = null;
if ($type=='firstLoginConfigStep' && $step==$CONFIG_STEPS['finish']) {
// if on last step of configuration, normally would get an exception (no-access-to-company-with-no-license);
// we need to prevent this, otherwise the config popup will not complete
$parms = [
'lastConfigStep' => true,
];
}
//$rc = $this->handlePageOpen($request, 'general', 'configuration', null, true); //T
$rc = $this->handleControllerAction($request, 'general', 'general', null, true, $parms); //
if ($rc!==true && $this->redirectRoute!=null) { //T
die('no access');
$result['info'] = 'no access';
$result['url'] = $this->router->generate('b_log_out');
return new Response($this->jsonEncoder(array(
'result' => $result,
)));
}
if ($type=='firstLoginConfigStep') {
//dump("firstLoginConfigStep, step: $step");
// CHECK it's a reg user
// used for 2 purposes:
// - first login when company and user data is set
// - new company creation
if (isset($data['companyId']) && $data['companyId']!=null) {
$companyId = $data['companyId'];
$company = $this->getDoctrine()->getRepository(Company::class)->findOneById($companyId);
} else if ($companyId!=null) {
$company = $this->getDoctrine()->getRepository(Company::class)->findOneById($companyId);
} else {
//$company = new Company;
$company = $this->company;
$companyId = $company->getId();
}
// do action necessary for this config step
if ($step==$CONFIG_STEPS['company']) {
// save the company's data
//dump('company');
// contract
$company->__set('name', $data['coName']);
$company->__set('postalCode', $data['coAddrPCode']);
$company->__set('city', $data['coAddrCity']);
$company->__set('address', $data['coAddr']);
$company->__set('country', $data['coCountry']);
$company->__set('taxNumber', $data['coTaxNumber']);
$company->__set('registrationNumber', $data['coRegistrationNumber']);
$company->__set('europeanTaxNumber', $data['coEUTaxNumber']);
$company->__set('contractSign1', $data['contractSign1']);
$company->__set('contractSign1Email', $data['contractSign1Email']);
$company->__set('contractSign1Phone', $data['contractSign1Phone']);
$company->__set('contractSign2', $data['contractSign2']);
$company->__set('contractSign2Email', $data['contractSign2Email']);
$company->__set('contractSign2Phone', $data['contractSign2Phone']);
// invoicing
//invoicingDataSameAsContract coInvoicingDataSameAsContract
$company->__set('invoicingCompanyName', $data['coNameForInvoicing']);
$company->__set('invoicingPostalCode', $data['coInvoicingAddrPCode']);
$company->__set('invoicingCity', $data['coInvoicingAddrCity']);
$company->__set('invoicingAddress', $data['coInvoicingAddr']);
$company->__set('invoicingCountry', $data['coInvoicingCountry']);
$company->__set('invoicingTaxNumber', $data['coInvoicingTaxNumber']);
$company->__set('invoicingEuropeanTaxNumber', $data['coInvoicingEUTaxNumber']);
// shipping
//coShippingDataSameAsContract coShippingDataSameAsContract
$company->__set('shippingCompanyName', $data['coNameForShipping']);
$company->__set('shippingContactName', $data['coContactNameForShipping']);
$company->__set('shippingPostalCode', $data['coShippingAddrPCode']);
$company->__set('shippingCity', $data['coShippingAddrCity']);
$company->__set('shippingAddress', $data['coShippingAddr']);
$company->__set('shippingCountry', $data['coShippingCountry']);
if ($company->__get('configurationStep')==null || $company->__get('configurationStep')<$step+1) {
$company->__set('configurationStep', $step+1);
}
// set first type to active trial --
//$company->__set('shippingAddress', );
$rc = $company->save( $this->getDoctrine()->getManager() );
if (!$rc) {
die('error updating company');
}
// save company info entry
$settingsValue = $this->timeCalc->currentGmDateTimeFull.';u'.$this->getUser()->getId();
$this->settingsLoader->updateSetting('config-step', 'company', $settingsValue, $company, false);
} else if ($step==$CONFIG_STEPS['tofu']) {
//dump('tofu');
// save TofU acceptance
$settingsValue = $this->timeCalc->currentGmDateTimeFull.';u'.$this->getUser()->getId();
$this->settingsLoader->updateSetting('config-step', 'tofu', $settingsValue, $company, true);
// check if document exists (we don't want many copies, at this time)
$tofuDocuments = $this->getDoctrine()->getRepository(Document::class)->findBy([
'company' => $company,
'type' => DocumentTypeEnum::TOFU,
'deleted' => 0,
]);
if ($tofuDocuments==null) {
// create document for the TofU
$document = new Document();
$document->setCompany($company);
$document->setName(''); // cannot be null
$document->setType(DocumentTypeEnum::TOFU);
$rc = $document->save( $this->getDoctrine()->getManager() );
if (!$rc) {
die('error updating document');
}
// generate the PDF sheet
$parms = [];
$documentBuilder->setParentController($this);
$documentBuilder->setAccount($company->getAccount());
$documentBuilder->setCompany($company);
$documentBuilder->setDocument($document);
$documentBuilder->build($parms);
}
// update config step in the company
if ($company->__get('configurationStep')==null || $company->__get('configurationStep')<$step+1) {
$company->__set('configurationStep', $step+1);
$rc = $company->save( $this->getDoctrine()->getManager() );
if (!$rc) {
die('error updating company');
}
}
} else if ($step==$CONFIG_STEPS['contract']) {
//dump('contract');
// save contract acceptance
$settingsValue = $this->timeCalc->currentGmDateTimeFull.';u'.$this->getUser()->getId();
$this->settingsLoader->updateSetting('config-step', 'contract', $settingsValue, $company, false);
// check if document exists (we don't want many copies, at this time)
$contractDocuments = $this->getDoctrine()->getRepository(Document::class)->findBy([
'company' => $company,
'type' => DocumentTypeEnum::CONTRACT,
'deleted' => 0,
]);
if ($contractDocuments==null) {
// create document for the contract
$document = new Document();
$document->setCompany($company);
$document->setName(''); // cannot be null
$document->setType(DocumentTypeEnum::CONTRACT);
$rc = $document->save( $this->getDoctrine()->getManager() );
if (!$rc) {
die('error updating document');
}
// generate the PDF sheet
$parms = [];
$documentBuilder->setParentController($this);
$documentBuilder->setAccount($company->getAccount());
$documentBuilder->setCompany($company);
$documentBuilder->setDocument($document);
$documentBuilder->build($parms);
}
// update config step in the company
if ($company->__get('configurationStep')==null || $company->__get('configurationStep')<$step+1) {
$company->__set('configurationStep', $step+1);
$rc = $company->save( $this->getDoctrine()->getManager() );
if (!$rc) {
die('error updating company');
}
}
} else if ($step==$CONFIG_STEPS['gdpr']) {
//dump('gdpr');
// save gdpr acceptance
$settingsValue = $this->timeCalc->currentGmDateTimeFull.';u'.$this->getUser()->getId();
$this->settingsLoader->updateSetting('config-step', 'gdpr', $settingsValue, $company, false);
// check if document exists (we don't want many copies, at this time)
$gdprDocuments = $this->getDoctrine()->getRepository(Document::class)->findBy([
'company' => $company,
'type' => DocumentTypeEnum::GDPR,
'deleted' => 0,
]);
if ($gdprDocuments==null) {
// create document for the contract
$document = new Document();
$document->setCompany($company);
$document->setName(''); // cannot be null
$document->setType(DocumentTypeEnum::GDPR);
$rc = $document->save( $this->getDoctrine()->getManager() );
if (!$rc) {
die('error updating document');
}
// generate the PDF sheet
$parms = [];
$documentBuilder->setParentController($this);
$documentBuilder->setAccount($company->getAccount());
$documentBuilder->setCompany($company);
$documentBuilder->setDocument($document);
$documentBuilder->build($parms);
}
// update config step in the company
if ($company->__get('configurationStep')==null || $company->__get('configurationStep')<$step+1) {
$company->__set('configurationStep', $step+1);
$rc = $company->save( $this->getDoctrine()->getManager() );
if (!$rc) {
die('error updating company');
}
}
} else if ($step==$CONFIG_STEPS['cookies']) {
//dump('cookies');
// save cookies acceptance
$settingsValue = $this->timeCalc->currentGmDateTimeFull.';u'.$this->getUser()->getId();
$this->settingsLoader->updateSetting('config-step', 'cookies', $settingsValue, $company, false);
// update config step in the company
if ($company->__get('configurationStep')==null || $company->__get('configurationStep')<$step+1) {
$company->__set('configurationStep', $step+1);
$rc = $company->save( $this->getDoctrine()->getManager() );
if (!$rc) {
die('error updating company');
}
}
} else if ($step==$CONFIG_STEPS['licenseType']) {
//dump('licenseType');
// save license type
$company->__set('licenseType', $data['licenseType']);
if ($company->__get('configurationStep')==null || $company->__get('configurationStep')<$step+1) {
$company->__set('configurationStep', $step+1);
}
$rc = $company->save( $this->getDoctrine()->getManager() );
if (!$rc) {
die('error updating company');
}
} else if ($step==$CONFIG_STEPS['settings']) {
// copy global parameters (day titles, etc.) to this company
if ($company->__get('localParamsChanged')!=true) {
//dump('copyGlobalParametersToLocal');
$this->dataSynchronizer->copyGlobalParametersToLocal($company, false); //JNOTE: false at end, since we don't have day assignments yet
}
//dump('settings');
//dump($data); //die();
// save protocol fields
$company->__set('protocolCreator', $data['coProtocolCreator']);
$company->__set('protocolApprover', $data['coProtocolApprover']);
$company->__set('localParamsChanged', true); //_
if ($company->__get('configurationStep')==null || $company->__get('configurationStep')<$step+1) {
$company->__set('configurationStep', $step+1);
}
$rc = $company->save( $this->getDoctrine()->getManager() );
if (!$rc) {
die('error updating company');
}
//die();
// save settings
$changesMade = [];
foreach($data as $settingName=>$settingValue) {
if (in_array($settingName, ['coProtocolCreator', 'coProtocolApprover'])) continue;
$settingNameArr = explode('-', $settingName);
$this->settingsLoader->updateSetting($settingNameArr[0], $settingNameArr[1], $settingValue, $company, true); // overwrite with later value
}
//JNOTE: add logging
} else if ($step==$CONFIG_STEPS['finish']) {
$company->__setDateTime('firstLoginConfigAt', $this->timeCalc->currentDateTime);
if ($company->__get('configurationStep')==null || $company->__get('configurationStep')<$step+1) {
$company->__set('configurationStep', $step+1);
}
$rc = $company->save( $this->getDoctrine()->getManager(), false );
if (!$rc) {
die('error updating company');
}
}
} else if ($type=='keepAlive') {
// nothing is needed here
$this->session->set('last-user-action-time', time());
} else { //T
// error
$result['msg'] = $this->translator->trans('message.genericError', array(), 'general');
$result['info'] = 'bad action';
return new Response($this->jsonEncoder(array(
'result' => $result,
)));
}
$result['success'] = true;
return new Response($this->jsonEncoder(array(
'result' => $result,
'data' => $returnData,
)));
}
/**
* Called periodically during page open
* @Route("/general/check-session", name="general.session", methods={"POST"})
*/
public function general_check_session_action(Request $request)
{
$rc = $this->handleControllerAction($request, 'general', 'check-session', null, true); //
if ($rc!==true && $this->redirectRoute!=null) { //T
die('no access');
$result['info'] = 'no access';
$result['url'] = $this->router->generate($this->redirectRoute);
return new Response($this->jsonEncoder(array(
'result' => $result,
)));
}
$returnData = [
'currentTimeUx' => time(),
'lastUserActionTimeUx' => $this->session->get('last-user-action-time'), // last user action time
'newEmails' => false,
'session_id' => session_id(),
];
// check if there are new messages
$this->messageHelper->getNewMessage($returnData['newEmails'], $this->getUser());
//sleep(5);
$result['success'] = true;
return new Response($this->jsonEncoder(array(
'result' => $result,
'data' => $returnData,
)));
}
/**
* Check to see at certain times, e.g. if logout expiry warning popup can be opened
* @Route("/general/check-status", name="general.status", methods={"POST"})
*/
public function general_check_status_action(Request $request)
{
$rc = $this->handleControllerAction($request, 'general', 'check-session', null, true); //
if ($rc!==true && $this->redirectRoute!=null) { //T
//die('no access');
$result['info'] = 'no access';
$result['url'] = $this->router->generate($this->redirectRoute);
return new Response($this->jsonEncoder(array(
'result' => $result,
)));
}
$returnData = [
'currentTimeUx' => time(),
'lastUserActionTimeUx' => $this->session->get('last-user-action-time'), // last user action time
];
//sleep(5);
$result['success'] = true;
return new Response($this->jsonEncoder(array(
'result' => $result,
'data' => $returnData,
)));
}
// ******************************************
// REGISTRATION
// ******************************************
/**
* @Route("/register", name="b_register")
*/
public function register(Request $request, \Twig_Environment $twig, EmailNotifier $email)
{
//die('');
//dump($request);
//dump($this->getUser());
//$this->handlePageOpen($request, 'tofu');
//$tofuHTML = $tofuTemplate->renderBlock('main', array());
$this->setLanguageAndLocale($request);
$initialMessage = '';
$initialMessageType = '';
$initialData = [
"companyName" => '',
"username" => '',
//"plainPassword" => '',
"email" => '',
"emailForNotifications" => '',
"phone" => '',
"country" => '',
"city" => '',
"address" => '',
"postalCode" => '',
];
if ($this->session->get('reg-form-error')!=null) {
$initialMessage = $this->session->get('reg-form-error');
$initialMessage = "showMsg('$initialMessage', false);";
$initialMessageType = 'error';
$initialData = $this->session->get('reg-form-data');
$this->session->set('reg-form-error', null);
$this->session->set('reg-form-data', null);
//dump($initialMessage);
//dump($initialData);
}
/*$email->sendEmail('registration',
$this->translator->trans('registrationEmail.subject', array(), 'emails'),
$this->translator->trans('registrationEmail.body', array(), 'emails'),
[
'FirstName' => 'Joe',
'LoginLink' => $_SERVER['APP_HOME_URL'].'/login',
'SiteName' => str_replace(['http://', '/'], '', $_SERVER['APP_HOME_URL']),
], [
'janusz@viewpointmultimedia.com' => 'janusz at vpmm',
]
);
//die();*/
$data = [];
if ($this->session->get('reg-form-data')!=null) {
$data = $this->session->get('reg-form-data');
}
// countries
$countriesArray = $this->formsHelper->getCountries($this->currentLanguage);
// cities
$citiesArray = $this->formsHelper->getCities($this->mainCountry);
// language strings
$allMessages = $this->translator->getCatalogue()->all();
$languageStrings['general'] = $allMessages['general'];
$languageStrings['registration'] = $allMessages['registration'];
$response = new Response();
return $this->render('frontend/register.html.twig', array(
'data' => $data,
'page_title' => $this->translator->trans('application.name', array(), 'general').' - '.
$this->translator->trans('page.title', array(), 'register'),
'initialMessage' => $initialMessage,
'initialMessageType' => $initialMessageType,
'data' => $initialData,
'countriesArray' => $countriesArray,
'citiesArray' => $citiesArray,
'languageStrings_js' => json_encode($languageStrings),
'currentLanguage' => $this->currentLanguage,
), $response);
}
/**
* @Route("/register/process", name="b_register_process")
*/
public function register_process(Request $request, \Twig_Environment $twig, UserPasswordEncoderInterface $passwordEncoder,
EmailNotifier $email)
{
$log = false;
//die('');
//dump($request);
//dump($this->getUser());
//die();
$this->setLanguageAndLocale($request);
$data = array(
'companyName' => $request->request->get('company'),
'username' => $request->request->get('username'),
'plainPassword' => $request->request->get('plainPassword'),
'email' => $request->request->get('email'),
'emailForNotifications' => $request->request->get('emailForNotifications'),
'phone' => $request->request->get('phone'),
'country' => $request->request->get('country'),
'city' => $request->request->get('city'),
//'city2' => $request->request->get('city2'),
'address' => $request->request->get('address'),
'postalCode' => $request->request->get('postalCode'),
);
if ($log) dump('data', $data);
//die();
// check CSRF token
$token = $request->request->get('_csrf_token');
if (!$this->isCsrfTokenValid('register', $token)) {
$this->session->set('reg-form-error', $this->translator->trans('message.genericError', array(), 'general')); //JNOTE
$this->session->set('reg-form-data', $data);
if ($log) dd('invalid csrf token');
return $this->redirectToRoute('b_register');
}
$em = $this->getDoctrine()->getManager();
// load system user
$systemUsers = $this->getDoctrine()->getRepository(User::class)->findById($_SERVER['APP_SYSTEM_USER_ID']);
$systemUser = $systemUsers[0];
//dump($systemUsers, $systemUser); die();
// check that a company with this name doesn't already exist
$duplicateCompanies = $this->getDoctrine()
->getRepository(Company::class)
->findBy([
'name' => $data['companyName'],
'deleted' => 0,
]);
if ($duplicateCompanies!=null) { //T
foreach($duplicateCompanies as $duplicateCompany) {
// there is a company with same name, return error
$this->session->set('reg-form-error', $this->translator->trans('message.companyNameExists', array(), 'registration'));
$this->session->set('reg-form-data', $data);
if ($log) dd('dup company name');
return $this->redirectToRoute('b_register');
}
} //
// check that this username doesn't already exist
$duplicateUsers = $this->getDoctrine()
->getRepository(User::class)
->findBy([
'email' => $data['email'],
'deleted' => 0,
]);
if ($duplicateUsers!=null) { //T
//dump('duplicateUsers', $duplicateUsers); //die();
foreach($duplicateUsers as $duplicateUser) {
// there is a user with same email address, return error
$this->session->set('reg-form-error', $this->translator->trans('message.emailAddressExists', array(), 'registration'));
$this->session->set('reg-form-data', $data);
//dd($this->translator->trans('message.emailAddressExists', array(), 'registration'));
if ($log) dd('dup email addr');
return $this->redirectToRoute('b_register');
}
} //
//die('---');
// create account
$account = new Account();
$account->__set('country', $data['country']);
$account->__set('createdBy', $systemUser);
$account->__set('type', AccountTypeEnum::REGULAR); //COM-817
if (!$account->save($em)) {
//die('account save');
$this->session->set('reg-form-error', $this->translator->trans('message.genericError', array(), 'general'));
$this->session->set('reg-form-data', $data);
if ($log) dd('account save error');
return $this->redirectToRoute('b_register');
}
// NOTE: initial idea was to add logic for payment, e.g. company and user shouldn't be created until money is paid;
// but this can't work like this - we need a user to place an order for a company; a company must belong to an account, etc.
// create company
$company = new Company();
$company->__set('account', $account);
$company->__set('name', $data['companyName']);
$company->__set('email', $data['emailForNotifications']);
$company->__set('phone', $data['phone']);
$company->__set('country', $data['country']);
$company->__set('adminType', CompanyAdminTypeEnum::CUSTOMER_TEST); // COM-479
//if ($data['country']=='hu') {
$company->__set('city', $data['city']);
//} else {
// $company->__set('city', $data['city2']);
//}
$company->__set('address', $data['address']);
$company->__set('postalCode', $data['postalCode']);
///$company->__set('status', 'created'); //JNOTE
$company->__set('createdBy', $systemUser);
$company->__set('isActive', false); // inactive by default (can log in only to configure the account)
$company->__set('configurationStep', 0); // start of configuration process
if (!$company->save($em)) {
//die('company save');
$this->session->set('reg-form-error', $this->translator->trans('message.genericError', array(), 'general'));
$this->session->set('reg-form-data', $data);
if ($log) dd('company save error');
return $this->redirectToRoute('b_register');
}
// create user
$user = new User();
$user->__set('account', $account);
$user->__set('username', $data['username']);
$user->__set('password', $passwordEncoder->encodePassword($user, $data['plainPassword']) );
$user->__set('roles', UserRoleEnum::ROLE_ACCOUNT_OWNER);
$user->__set('email', $data['email']);
$user->__set('currentCompanyViewed', $company); // set company to the one just created (default - can be changed later)
$user->__set('createdBy', $systemUser);
if (!$user->save($em)) {
//die('user save');
$this->session->set('reg-form-error', $this->translator->trans('message.genericError', array(), 'general'));
$this->session->set('reg-form-data', $data);
if ($log) dd('user save error');
return $this->redirectToRoute('b_register');
}
// update the account with the user and company created above
$accounts = $this->getDoctrine()->getRepository(Account::class)->findById($account->getId());
if ($accounts==null) {
//die('error getting account');
$this->session->set('reg-form-error', $this->translator->trans('message.genericError', array(), 'general'));
$this->session->set('reg-form-data', $data);
if ($log) dd('account read error');
return $this->redirectToRoute('b_register');
}
//dump($accounts);
$accounts[0]->__set('primaryCompany', $company);
$accounts[0]->__set('primaryUser', $user);
//$accounts[0]->__set('updatedBy', $systemUser);
//dump('------', $accounts[0], $company, $user);
if (!$accounts[0]->save($em, false)) {
// ignore error
if ($log) dd('account update error');
die('error updating account');
}
// send email welcoming the person, and telling him to log into his account to configure it (if not already done so)
if (0) {
$email->sendEmail('registration',
$this->translator->trans('registrationEmail.subject', array(), 'emails'),
$this->translator->trans('registrationEmail.body', array(), 'emails'),
[
'FirstName' => 'Joe',
'LoginLink' => $_SERVER['APP_HOME_URL'].'/login',
'SiteName' => str_replace(['http://', '/'], '', $_SERVER['APP_HOME_URL']),
], [
$data['emailForNotifications'] => $data['companyName'],
]
);
if ($log) ('after email send');
}
if ($log) dd('end of reg process');
//dd('---');
return $this->redirectToRoute('b_register_ack');
}
/**
* @Route("/register-thankyou", name="b_register_ack")
*/
public function register_ack(Request $request, \Twig_Environment $twig)
{
//dump($request);
//dump($this->getUser());
//$this->handlePageOpen($request, 'tofu');
$this->setLanguageAndLocale($request);
$initialMessage = $this->translator->trans('info.registrationAckMessage', array(), 'registration');
$initialMessageType = '';
$response = new Response();
return $this->render('frontend/register-ack.html.twig', array(
'page_title' => $this->translator->trans('application.name', array(), 'general').' - '.
$this->translator->trans('page.title', array(), 'register'),
'initialMessage' => $initialMessage,
'initialMessageType' => $initialMessageType,
), $response);
}
// ******************************************
// PASSWORD RESET
// ******************************************
/**
* @Route("/pwdreset", name="b_password_reset.pg")
*/
public function password_reset_pg(Request $request, \Twig_Environment $twig)
{
//dump($request);
//dump($this->getUser());
//$this->handlePageOpen($request, 'tofu');
//$tofuHTML = $tofuTemplate->renderBlock('main', array());
$this->setLanguageAndLocale($request);
$initialMessage = '';
$initialMessageType = '';
if ($this->session->get('pwdreset-form-error')!=null) {
$initialMessage = $this->session->get('pwdreset-form-error');
$initialMessageType = 'error';
}
$data = [];
if ($this->session->get('pwdreset-form-data')!=null) {
$data = $this->session->get('pwdreset-form-data');
}
// language strings
$allMessages = $this->translator->getCatalogue()->all();
$languageStrings['general'] = $allMessages['general'];
$languageStrings['password-reset'] = $allMessages['password-reset'];
$response = new Response();
return $this->render('frontend/password-reset-request.html.twig', array(
'data' => $data,
'page_title' => $this->translator->trans('application.name', array(), 'general').' - '.
$this->translator->trans('page.title', array(), 'register'),
'initialMessage' => $initialMessage,
'initialMessageType' => $initialMessageType,
'languageStrings_js' => json_encode($languageStrings),
), $response);
}
/**
* @Route("/pwdreset/request/process", name="b_pwdreset_request_process.action", methods={"POST"})
*/
public function pwdreset_request_process_action(Request $request, UserPasswordEncoderInterface $passwordEncoder,
EmailNotifier $email)
{
//die('emailing disabled temporarily');
//dump($request);
//dump($this->getUser());
//die('pwdreset_request_process_action');
// check CSRF token
$token = $request->request->get('_csrf_token');
if (!$this->isCsrfTokenValid('password-reset', $token)) {
$this->session->set('pwdreset-form-error', 'error');
$this->session->set('pwdreset-form-data', []);
// JNOTE: message!!!!
return $this->redirectToRoute('b_password_reset.pg');
}
$data = array(
//'username' => $request->request->get('username'),
'email' => $request->request->get('email'),
);
//dump($data, $token);
//die();
$em = $this->getDoctrine()->getManager();
// load system user
$systemUsers = $this->getDoctrine()->getRepository(User::class)->findById($_SERVER['APP_SYSTEM_USER_ID']);
$systemUser = $systemUsers[0];
// find the user for this request
$foundUser = $this->getDoctrine()
->getRepository(User::class)
->findOneBy([
'email' => $data['email'],
'deleted' => 0,
]);
if ($foundUser==null) { //T
// normally, this should be a reported error
// BUT it can happen that this page is used to test out if email addresses are in this system
// to make this much less useful, report to the user that everything went ok
return $this->redirectToRoute('b_pwdreset_request_ack.pg');
}
//dump('$foundUser', $foundUser);
//die('---');
// create password reset link
$pwdResetlink = new Link();
$pwdResetlink->__set('company', null);
$pwdResetlink->__set('type', 0); //JNOTE
$pwdResetlink->generateCode();
$pwdResetlink->__set('relatedUser', $foundUser);
$pwdResetlink->__set('createdBy', $systemUser);
//dump('$pwdResetlink', $pwdResetlink);
if (!$pwdResetlink->save($em)) { //T
$this->session->set('page-title', ['password-reset', 'page.title.error']);
$this->session->set('page-content', ['general', 'message.genericError']);
return $this->redirectToRoute('b_error.pg');
}
// send email with the password reset link
if (1) {
// LINK SECURITY
// We use two separate strings, to be sure that we're secure and unique; both are binary strings, encoded using md5
// - pwdResetCode: unique code, the main thing looked up
// - encodedEmailAddr: related user's email address, also encoded using md5
// Link verification is two-fold:
// - find a link with the matching pwdResetCode
// - confirm that the user associated with the link has the same email address (hashed using md5)
$linkUrl = $_SERVER['APP_HOME_URL'];
$linkUrl .= $this->router->generate('b_pwdreset_selectNewPassword.pg', [
'pwdResetCode' => $pwdResetlink->getCode(),
'encodedEmailAddr' => md5($data['email']),
]);
//dump('linkUrl', $linkUrl); die();
$userName = $foundUser->getName();
if ($userName=='') $userName = $foundUser->getUsername();
$email->sendEmail('passwordReset',
$this->translator->trans('passwordResetEmail.subject', array(), 'emails'),
$this->translator->trans('passwordResetEmail.body', array(), 'emails'),
[
'Name' => $userName,
'CodeBeforeLink' => "<a href='$linkUrl'>",
'CodeAfterLink' => "</a>",
'LinkAddress' => $linkUrl,
'SiteName' => str_replace(['https://', 'http://', '/'], '', $_SERVER['APP_HOME_URL']),
], [
$data['email'] => $userName,
]
);
//die('=====');
}
//die('--');
return $this->redirectToRoute('b_pwdreset_request_ack.pg');
}
/**
* @Route("/pwdreset/request/thank-you", name="b_pwdreset_request_ack.pg")
*/
public function pwdreset_request_ack_pg(Request $request, \Twig_Environment $twig)
{
//dump($request);
//dump($this->getUser());
//$this->handlePageOpen($request, 'tofu');
$this->setLanguageAndLocale($request);
$initialMessage = '';
$initialMessageType = '';
$initialMessage = $this->translator->trans('message.linkSent', array(), 'password-reset');
$initialMessageType = '';
$response = new Response();
return $this->render('frontend/password-reset-request-ack.html.twig', array(
'page_title' => $this->translator->trans('application.name', array(), 'general').' - '.
$this->translator->trans('page.title.linkSent', array(), 'password-reset'),
'initialMessage' => $initialMessage,
'initialMessageType' => $initialMessageType,
), $response);
}
/**
* @Route("/pwdreset/act/{pwdResetCode}/{encodedEmailAddr}", name="b_pwdreset_selectNewPassword.pg")
*/
public function b_pwdreset_selectNewPassword_pg(Request $request, $pwdResetCode, $encodedEmailAddr, \Twig_Environment $twig)
{
//dump('b_pwdreset_selectNewPassword_pg', $request, $pwdResetCode);
//dump($this->getUser());
//die('new pass sel');
//$this->handlePageOpen($request, 'tofu');
$this->setLanguageAndLocale($request);
$pwdResetlink = null;
$relatedUser = null;
// validate the link
$rc = $this->validatePwdResetLink($pwdResetCode, $encodedEmailAddr,
$pwdResetlink, $relatedUser);
if ($rc!==true) { //T
// if $rc is not true, it has the proper redirect return Response
return $rc;
} //T
// language strings
$allMessages = $this->translator->getCatalogue()->all();
$languageStrings['general'] = $allMessages['general'];
$languageStrings['password-reset'] = $allMessages['password-reset'];
$response = new Response();
return $this->render('frontend/password-reset.html.twig', array(
'page_title' => $this->translator->trans('application.name', array(), 'general').' - '.
$this->translator->trans('page.title', array(), 'register'),
'initialMessage' => '', //$initialMessage,
'initialMessageType' => '', //$initialMessageType,
'languageStrings_js' => json_encode($languageStrings),
'c1' => $pwdResetCode,
'c2' => $encodedEmailAddr,
), $response);
}
/**
* @Route("/pwdreset/sel/process", name="b_pwdreset_selectNewPassword.action", methods={"POST"})
*/
public function b_pwdreset_selectNewPassword_action(Request $request, UserPasswordEncoderInterface $passwordEncoder)
{
//dump($request);
//dump($this->getUser());
//die('b_pwdreset_selectNewPassword_action');
// check CSRF token
$token = $request->request->get('_csrf_token');
if (!$this->isCsrfTokenValid('password-reset2', $token)) {
die('invalid token');
return $this->redirectToRoute('b_register');
}
$data = [
'plainPassword' => $request->request->get('plainPassword'),
'plainPassword2' => $request->request->get('plainPassword2'),
'pwdResetCode' => $request->request->get('c1'),
'encodedEmailAddr' => $request->request->get('c2'),
];
//dump($data); //, $token);
//die();
if ($data['plainPassword'] != $data['plainPassword2']) {
die('passwords do not match');
}
$em = $this->getDoctrine()->getManager();
$pwdResetlink = null;
$relatedUser = null;
// validate the link
$rc = $this->validatePwdResetLink($data['pwdResetCode'], $data['encodedEmailAddr'],
$pwdResetlink, $relatedUser);
if ($rc!==true) { //T
// if $rc is not true, it has the proper redirect return Response
return $rc;
} //T
// load system user
$systemUsers = $this->getDoctrine()->getRepository(User::class)->findById($_SERVER['APP_SYSTEM_USER_ID']);
$systemUser = $systemUsers[0];
// change the user password
//dump('relatedUser 1', $relatedUser);
$relatedUser->__set('password', $passwordEncoder->encodePassword($relatedUser, $data['plainPassword']) );
$relatedUser->__set('updatedBy', $systemUser);
//dump('relatedUser 2', $relatedUser);
if (!$relatedUser->save($em)) { //T
// email address hash in email not the same as in the db, send to error page
$this->session->set('page-title', ['password-reset', 'page.title.error']);
$this->session->set('page-content', ['general', 'message.genericError']);
return $this->redirectToRoute('b_error.pg');
}
// invalidate the link
if (1) {
// mark the link as deleted
$pwdResetlink->setDeleted(true);
if (!$pwdResetlink->save($em)) {
die('error marking link as deleted');
}
} else {
// delete the link completely
}
//die('===');
return $this->redirectToRoute('b_pwdreset_selectNewPassword_ack.pg');
}
/**
* @Route("/pwdreset/sel/thank-you", name="b_pwdreset_selectNewPassword_ack.pg")
*/
public function b_pwdreset_selectNewPassword_ack_pg(Request $request, \Twig_Environment $twig)
{
//dump($request);
//dump($this->getUser());
//$this->handlePageOpen($request, 'tofu');
$this->setLanguageAndLocale($request);
$initialMessage = '';
$initialMessageType = '';
$response = new Response();
return $this->render('frontend/password-reset-ack.html.twig', array(
'page_title' => $this->translator->trans('application.name', array(), 'general').' - '.
$this->translator->trans('page.title', array(), 'register'),
'initialMessage' => $initialMessage,
'initialMessageType' => $initialMessageType,
), $response);
}
private function validatePwdResetLink($pwdResetCode, $encodedEmailAddr,
&$pwdResetlink, &$relatedUser) {
// load the link
$pwdResetlink = $this->getDoctrine()->getRepository(Link::class)->findOneByCode($pwdResetCode);
//dump('pwdResetlink', $pwdResetlink);
if ($pwdResetlink==null) { //T
// no link found, send to error page
$this->session->set('page-title', ['password-reset', 'page.title.error']);
$this->session->set('page-content', ['password-reset', 'message.invalidLink']);
return $this->redirectToRoute('b_error.pg');
} else if ($pwdResetlink->getDeleted()==true) { //T
// link already used, send to error page
$this->session->set('page-title', ['password-reset', 'page.title.linkAlreadyUsed']);
$this->session->set('page-content', ['password-reset', 'message.linkAlreadyUsed']);
return $this->redirectToRoute('b_error.pg');
}
// check for link expiry
$this->timeCalc->refreshTimeZone();
$linkAgeInMinutes = $this->timeCalc->getMinutesDifferenceSimple($this->timeCalc->currentDateTime, $pwdResetlink->__getDateTimeFormatted('createdAt'));
//dump(date_default_timezone_get());
//dump("O: ".$pwdResetlink->__getDateTimeFormatted('createdAt').", N:".$this->timeCalc->currentDateTime.", diff: $linkAgeInMinutes min");
//dump(date("Y-m-d H:i")); die();
//dump('linkAgeInMinutes', $linkAgeInMinutes); die();
if ($linkAgeInMinutes > 60) { //T
// link expired, send to error page
$this->session->set('page-title', ['password-reset', 'page.title.linkExpired']);
$this->session->set('page-content', ['password-reset', 'message.linkExpired']);
return $this->redirectToRoute('b_error.pg');
}
//die('==');
// get the user connected to this link
$relatedUser = $pwdResetlink->__get('relatedUser');
//dump('relatedUser', $relatedUser);
if ($relatedUser==null) {
// no link found, send to error page
$this->session->set('page-title', ['password-reset', 'page.title.error']);
$this->session->set('page-content', ['password-reset', 'message.invalidLink']);
return $this->redirectToRoute('b_error.pg');
}
$relatedUserEncodedEmail = md5($relatedUser->getEmail());
if (!hash_equals($relatedUserEncodedEmail, $encodedEmailAddr)) { //T
// email address hash in email not the same as in the db, send to error page
$this->session->set('page-title', ['password-reset', 'page.title.error']);
$this->session->set('page-content', ['password-reset', 'message.invalidLink']);
return $this->redirectToRoute('b_error.pg');
} else {
//dump("hashes same: db[$relatedUserEncodedEmail] link[$encodedEmailAddr]");
}
return true;
}
// ******************************************
// MISCELLANEOUS
// ******************************************
/**
* @Route("/language/{lang}", name="language.change.action", methods={"POST"})
*/
public function language_change_action(Request $request, $lang)
{
//dump($request);
$result = $this->getDefaultAjaxReturnRec();
$this->session->set('language', $lang);
/*$rc = $this->handleControllerAction($request, $this->module, 'edit', $entities[0], true);
if ($rc!==true) {
$result['error'] = 'no-access';
$result['url'] = $this->redirectRoute;
return new Response($this->jsonEncoder($result));
}*/
$result['success'] = true;
return new Response($this->jsonEncoder(array(
'result' => $result,
)));
}
/**
* @Route("/driver-vehicle/filter/{driverVehicleId}", name="driver-vehicle-filter.action", methods={"POST"})
*/
public function filter_action(Request $request, $driverVehicleId)
{
$result = $this->getDefaultAjaxReturnRec();
/*$rc = $this->handleControllerAction($request, $this->module, 'edit', $this->emptyEntity);
if ($rc!==true) {
return $this->redirectToRoute($this->redirectRoute);
}*/
if (substr($driverVehicleId, 0, 1)=='V') {
$this->session->set('selected-vehicle', substr($driverVehicleId, 1));
} else {
$this->session->set('selected-driver', $driverVehicleId);
}
//$this->session->set('selected-range', "$startDate;$endDate");
$result['success'] = true;
//dump($result); die();
return new Response($this->jsonEncoder(array(
'result' => $result,
)));
}
/** COM-469
* @Route("/message-reaction", name="message-reaction.action", methods={"POST"})
*/
public function message_reaction_action(Request $request)
{
$result = $this->getDefaultAjaxReturnRec();
$rc = $this->handleControllerAction($request, 'general', 'message-reaction', null, true); // COM-792: use 'message-reaction'
if ($rc!==true) {
die('no access');
}
$broadcastMessageId = $request->request->get('brMessageId');
$buttonAction = $request->request->get('buttonAction');
$dontShowAgain = (($request->request->get('dontShow') ?? 'false')=='true');
//dump('message_reaction_action data', $broadcastMessageId, $buttonAction, $dontShowAgain);
// load the message
$broadcastMsgRepository = $this->getDoctrine()->getRepository(BroadcastMessage::class);
$broadcastMsg = $broadcastMsgRepository->findOneById($broadcastMessageId);
if ($broadcastMsg==null) {
die();
}
// get the reaction
if ($buttonAction=='install') {
$reactionType = BroadcastMessageReactionEnum::REQUEST_FUNCTION;
} else if ($buttonAction=='skip') {
if ($dontShowAgain) {
$reactionType = BroadcastMessageReactionEnum::CLOSE_AND_HIDE;
} else {
$reactionType = BroadcastMessageReactionEnum::CLOSE;
}
} else {
die();
}
// save the reaction to db
$this->messageHelper->saveBroadcastMessageReaction($broadcastMsg, $this->company, $this->getUser(), $reactionType);
// save the reaction into session variable, no need to show the popup again, until the next login
$sessionVar = $this->session->get('broadcast-msgs');
if ($sessionVar==null) {
$sessionVar = [
$broadcastMessageId => $reactionType,
];
} else {
$sessionVar[$broadcastMessageId] = $reactionType;
}
$this->session->set('broadcast-msgs', $sessionVar);
//dump('sessionVar', $sessionVar);
// send notification email, if the function was requested
if (1 &&
$reactionType==BroadcastMessageReactionEnum::REQUEST_FUNCTION &&
isset($_SERVER["APP_COMPASS_NOTIFICATION_EMAIL_ADDRS"])) {
$this->emails->sendEmail('compass-notification',
$this->translator->trans('notification.featureRequested.subject', array(), 'emails'),
$this->translator->trans('notification.featureRequested.body', array(), 'emails'),
[
'CompanyName' => $this->company->getName(),
'FeatureName' => 'Statistics Module',
'UsersName' => $this->getUser()->getName(),
], null
);
}
// return
$result['success'] = true;
//dump($result); die();
return new Response($this->jsonEncoder(array(
'result' => $result,
)));
}
/** COM-695
* @Route("/system-tip-action", name="system-tip-action.action", methods={"POST"})
*/
public function system_tip_action_action(Request $request)
{
$result = $this->getDefaultAjaxReturnRec();
$rc = $this->handleControllerAction($request, 'general', 'list', null, true);
if ($rc!==true) {
die('no access');
}
$systemTipIds = $request->request->get('systemTipIds');
$actionType = $request->request->get('actionType');
$getNew = $request->request->get('getNew'); // how many new tips to get (none=false)
//dump("system_tip_reaction_action data ( systemTipIds, $actionType, $getNew)", $systemTipIds);
//die();
// since a Compass user has access to all companies, we don't want this user's actions
// (opening Bob popup, etc.) to be included in the stats - so we handle that user differently
if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_SUPER_ADMIN) {
// what happens depends on the system & the admin type of the company
// - on techsupp, all actions by Compass user are recorded
// - on DEV, ditto
// - on LIVE, actions by Compass user are recorded ONLY if co. admin type is Internal
// (they are ignored for types "live", "trial active", "trial expired"
$companyAdminType = $this->company->__get('adminType');
$allowActionSave = false;
if ($_SERVER['APP_SYSTEM_ID']=='TechSupp') { //T
// on TechSupp, always allow
$allowActionSave = true;
// JNOTE-TESTING:
//if ($companyAdminType==CompanyAdminTypeEnum::INTERNAL_TEST) { //T
// $allowActionSave = true;
//} else { //T
// $allowActionSave = false;
//}
//dump('TechSupp, allowActionSave: '.$allowActionSave);
} else if ($_SERVER['APP_SYSTEM_ID']=='DEV') { //T1
// on DEV, always allow
$allowActionSave = true;
//dump('DEV, allowActionSave: '.$allowActionSave);
} else if ($_SERVER['APP_SYSTEM_ID']=='LIVE') { //T 1
// on LIVE, only allow if company type is "Internal"
if ($companyAdminType==CompanyAdminTypeEnum::INTERNAL_TEST) { //T1
$allowActionSave = true;
} //T1
//dump('LIVE, allowActionSave: '.$allowActionSave);
} else {
die();
}
} else if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_ACCOUNT_OWNER ||
$this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_ADMIN) {
// for registered or admin users, record the action
$allowActionSave = true;
} else if ($this->getUser()->getRolesUnconverted()==UserRoleEnum::ROLE_USER) { // N/A
// for all other users, do not record (it should not even show)
// (ROLE_USER, ROLE_UPLOAD_ONLY, ROLE_UPLOAD_PROTOCOL)
$allowActionSave = false;
} else { //
// catch all
if ($_SERVER['APP_SYSTEM_ID']=='LIVE') {
// to be safe, do not allow on LIVE
$allowActionSave = false;
} else {
// allow on other systems
$allowActionSave = true;
}
}
// load the message
$systemTipRepository = $this->getDoctrine()->getRepository(SystemTip::class);
if ($actionType=='show') {
$tipStatus = SystemTipStatusEnum::SHOWN;
} else if ($actionType=='ack') {
$tipStatus = SystemTipStatusEnum::ACKED;
} else if ($actionType=='snooze') {
$tipStatus = SystemTipStatusEnum::SNOOZED;
} else {
die();
}
if ($allowActionSave) {
foreach($systemTipIds as $systemTipId) {
//dump($systemTipId);
//continue;
// update system tip
$systemTip = $systemTipRepository->findOneById($systemTipId);
if ($systemTip==null) {
die('null');
}
$systemTip->__set('status', $tipStatus);
$rc = $systemTip->save( $this->getDoctrine()->getManager(), false ); // no updated* field change
if (!$rc) {
die('error updating tip');
}
// add history entry for this tip
$systemTipLogEntry = new SystemTipLogEntry;
$systemTipLogEntry->__set('company', $this->company);
$systemTipLogEntry->__set('systemTip', $systemTip);
$systemTipLogEntry->__set('status', $tipStatus);
$rc = $systemTipLogEntry->save( $this->getDoctrine()->getManager(), false ); // no updated* field change
if (!$rc) {
die('error updating tip log entry');
}
//dump('updated');
unset($systemTip);
unset($systemTipLogEntry);
}
}
// get new tip if requested
if ($getNew!==false) {
$newTipInfo = $this->ai->getSystemTipsForCompany($this->company, true, $getNew);
//dump('newTip', $newTip);
$result['newTips'] = [];
if ($newTipInfo['tips']!==null && is_array($newTipInfo['tips']) && count($newTipInfo['tips'])>0) {
foreach($newTipInfo['tips'] as $newTip) {
// use this tip
$result['newTips'][] = $newTip;
// mark this tip as shown (if allowed)
if ($allowActionSave) {
// update system tip
$systemTip = $systemTipRepository->findOneById($newTip['id']);
if ($systemTip!=null) {
$systemTip->__set('status', SystemTipStatusEnum::SHOWN);
$rc = $systemTip->save( $this->getDoctrine()->getManager(), false ); // no updated* field change
if (!$rc) {
die('error updating tip');
}
// add history entry for this tip
$systemTipLogEntry = new SystemTipLogEntry;
$systemTipLogEntry->__set('company', $this->company);
$systemTipLogEntry->__set('systemTip', $systemTip);
$systemTipLogEntry->__set('status', SystemTipStatusEnum::SHOWN);
$rc = $systemTipLogEntry->save( $this->getDoctrine()->getManager(), false ); // no updated* field change
if (!$rc) {
die('error updating tip log entry');
}
//dump('updated');
unset($systemTip);
unset($systemTipLogEntry);
}
}
}
} else {
// no more tips
//$result['newTips'] = null;
}
}
// return
$result['success'] = true;
//dump($result); die();
return new Response($this->jsonEncoder(array(
'result' => $result,
)));
}
/**
* @Route("/ipn_otpsimple", name="b.otpsimple.ipn", methods={"POST"})
*/
function otp_simple_ipn(Request $request)
{
require_once($_SERVER['APP_HOME_DIR'].'vendor/OTPSimple/SimplePayV21.php');
require_once($_SERVER['APP_HOME_DIR'].'vendor/OTPSimple/config.php');
//dump('initial config', $config);
$date = new \DateTime();
$json = file_get_contents('php://input');
//dump('intitial json', $json);
//$this->symfonyLogger->info("otp_simple_ipn json: $json");
//$this->symfonyLogger->info($request->getContent());
//$this->symfonyLogger->info($request);
$json = json_decode($json,true);
//dump('json_decode json', $json);
$trid = $json['transactionId'];
$json['receiveDate'] = $date->format(('Y-m-d\TH:i:sO'));
$json = json_encode($json);
//$this->symfonyLogger->info("otp_simple_ipn 2: $json");
$trx = new \SimplePayIpn;
$trx->addConfig($config);
//dump('trx after addConfig', $trx);
//dump('json with receiveDate updated', $json);
$orderRepository = $this->getDoctrine()->getRepository(LicenseOrder::class);
$orderRepository->findOrderByTrid($trid,$result);
if (@$result) {
$details = json_decode($result->details,true);
$details['card_payment_IPN'] = $json;
$details = json_encode($details);
$result->setDetails($details);
$result->setStatus(98);
$em = $this->getDoctrine()->getManager();
$em->persist($result);
$em->flush();
}
if ($trx->isIpnSignatureCheck($json)) {
var_dump($trx);
$trx->runIpnConfirm();
var_dump($trx);
}
$signature = base64_encode(hash_hmac('sha384',$json,'7wUt7af1h1JuTn1v01128562ZtZ7J3jz',true));
$response = new Response();
$response->setContent($json);
$response->headers->set('Signature',$signature);
return $response;
}
/**
* @Route("/test-function", name="test-function")
*/
public function test(Request $request, ActivityGraph $graph)
{
die();
dump('PHP method_exists($graph, "loadVehicleActivities"): '.method_exists($graph, 'loadVehicleActivities'));
dump('---');
dump('get_class_methods($graph)', get_class_methods($graph));
dump('graph', $graph);
die();
}
}