<?php
namespace App\Controller;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\Persistence\ObjectManager;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
//use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\MonologBundle\SwiftMailer\Swift_Message;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogHandler;
use Monolog\ErrorHandler;
use Monolog\Logger;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use App\Entity\Currency;
use App\Entity\Eshop;
use App\Entity\Gallery;
use App\Entity\Gallery3D;
use App\Entity\GalleryItem;
use App\Entity\Language;
use App\Entity\Module;
use App\Entity\PriceLevel;
use App\Entity\Product;
use App\Entity\ProductGroup;
use App\Entity\RedactionList;
use App\Entity\Server;
use App\Entity\Service;
use App\Entity\User;
use Symfony\Bridge\Twig\Mime\BodyRenderer;
use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mailer\Mailer;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mime\Address;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
class DefaultController extends AbstractController
{
protected string $databaseUser = "root";
protected string $databasePassword = "pswdb33";
protected string $translateBaseUrl = 'https://translate.yandex.net/api/v1.5/tr.json/translate';
protected string $translateApiKey = 'trnsl.1.1.20200423T052136Z.ae351a8275ee45f3.fe0d2bd852ec5d9c88b7a00ebe8d5260fc589c35';
protected MailerInterface $mailer;
public function __construct(
protected ManagerRegistry $doctrine,
KernelInterface $appKernel,
MailerInterface $mailer
) {
$this->doctrine = $doctrine;
$this->appKernel = $appKernel;
$this->mailer = $mailer;
}
public function init(Request $request)
{
$session = $request->getSession();
$em = $this->doctrine->getManager();
/* we set server info */
//$session->set('label', null);
/*
print("<br>qqw php ver: ");
print_r(phpversion());
print("<br>qqw label: ".$session->get('label'));
*/
//$request->setLocale('cz');
// print(phpinfo());
//
// print("<br>qqw label: ".$session->get('label'));
//$em = $this->em;
//$session->remove('label');
/* setting default label/server/brand/ */
if(empty($session->get('label'))) {
/* we try to get http host and choose label */
//print("<br>qqw host: ".$_SERVER['HTTP_HOST']);
$hostServer = $em->getRepository(Server::class)->getServerFromHost($_SERVER['HTTP_HOST']);
// print("<br>qqw hostServer: ".$_SERVER['HTTP_HOST']);
// \Doctrine\Common\Util\Debug::dump($hostServer);
if (empty($hostServer)) {
$this->addFlash('error', 'Please add Server instance.');
return;
}
$session->set('label', $hostServer->getLabel());
//$session->set('label', 'webexciter.com');
// print("<br>QQW getting default label: ".$session->get('label'));
$server = $this->getServerByLabel($session->get('label'));
$session->set('server', $server);
/*
print('<hr>qqw getServices: ');
\Doctrine\Common\Util\Debug::dump($session->get('server')->getServices());
*/
/* we load languages into session */
$langList = $em->getRepository(Language::class)->getLanguageList();
$session->set('langList', $langList);
/* we load currencies into session */
$currencyList = $em->getRepository(Currency::class)->getCurrencyList();
$session->set('currencyList', $currencyList);
/* we setup server preferred language */
$lang = $em->getRepository(Language::class)->getLanguage($server->getPreferredLanguageId());
$session->set('lang', $lang);
// print("<br>QQW lang 1: ".$lang->getLangKey());
/*
print("<br>QQW locale 1: ".$request->getLocale());
if(empty($session->get('lang')->getLangKey())) {
$request->setLocale($session->get('lang')->getLangKey());
}
*/
$request->setLocale($session->get('lang')->getLangKey());
/* we setup server preferred currency */
$currency = $em->getRepository(Currency::class)->getCurrency($server->getPreferredCurrencyId());
$session->set('currency', $currency);
}
/*
print("<hr>qqw locale: ");
print_r($request->getLocale());
print("<hr>qqw label: ".$session->get('label'));
print("<hr>qqw langList: ");
print_r($session->get('langList'));
print("<hr>qqw currencyList: ");
print_r($session->get('currencyList'));
print("<hr>qqw lang: ");
print_r($session->get('lang'));
print("<hr>qqw currency: ");
print_r($session->get('currency'));
*/
//print("<br>QQW locale 2: ".$request->getLocale());
/* setting new label/server/brand/ */
if(!empty($request->query->get('newlabel'))) {
$session->set('label', $request->query->get('newlabel'));
//print("<br>QQW setting new label");
$server = $this->getServerByLabel($session->get('label'));
$session->set('server', $server);
/* we load languages into session */
$langList = $em->getRepository(Language::class)->getLanguageList();
$session->set('langList', $langList);
/* we load currencies into session */
$currencyList = $em->getRepository(Currency::class)->getCurrencyList();
$session->set('currencyList', $currencyList);
/* we setup server preferred language */
$lang = $em->getRepository(Language::class)->getLanguage($server->getPreferredLanguageId());
$session->set('lang', $lang);
/* we setup server preferred currency */
$currency = $em->getRepository(Currency::class)->getCurrency($server->getPreferredCurrencyId());
$session->set('currency', $currency);
}
/* setting new currency */
if(!empty($request->query->get('newcurrency'))) {
//print("<br>QQW setting new currency");
$currency = $em->getRepository(Currency::class)->getCurrencyByKey($request->query->get('newcurrency'));
if(!empty($currency)) {
$session->set('currency', $currency);
$this->addFlash('notice', 'Currency was changed to '.$currency->getCurrencyName().'.');
}
}
/* setting new eshop currency */
/* - it is done in EshopController @Route("/eshop/{eshopId}/eshopNewcurr", name="eshopNewcurr")
if(!empty($request->query->get('newEshopCurrency'))) {
//print("<br>QQW setting new eshop currency");
$currency = $em->getRepository('App:Currency')->getCurrencyByKey($request->query->get('newEshopCurrency'));
if(!empty($currency)) {
$session->set('eshopCurrency', $currency);
foreach($session->getFlashBag() as $message) {
print('<br>qqw message X');
}
$this->addFlash('notice', 'E-shop Currency was changed to '.$currency->getCurrencyName().'.');
}
}
*/
/* we set locale according to lang */
/* this is done in event listener */
//$request->setLocale($session->get('lang')->getLangKey());
//print("<br>QQW locale: ".$request->getLocale());
//$translator->getCatalogue($request->getLocale());
//print("<br>QQW label: ".$session->get('label'));
/* we set info */
}
public function getServerByLabel($label)
{
/* print("<br>QQW getting server from label: ".$label); */
$em = $this->doctrine->getManager();
$server = $em->getRepository(Server::class)->getServerFromLabel($label);
return $server;
}
public function getPageHeader(Request $request)
{
$session = $request->getSession();
$em = $this->doctrine->getManager();
$user = null;
$serviceCollectionn = null;
$moduleCollection = null;
/* we get current user */
if(!empty($session->get('user'))) {
$currentUserId = $session->get('user')->getUserId();
$user = $em->getRepository(User::class)->getUser($currentUserId);
$serviceCollection = $em->getRepository(Service::class)->getServiceList();
$moduleCollection = $em->getRepository(Module::class)->getLiveModuleList();
}
//we build service array
$services = array();
if(!empty($serviceCollection)) {
foreach($serviceCollection as $service) {
$isService = $em->getRepository(User::class)->userHasService($user, $service);
if($isService) {
$serviceId = $service->getServiceId();
$services[$serviceId] = $service;
}
}
}
//we build module array
$modules = array();
if(!empty($moduleCollection)) {
foreach($moduleCollection as $module) {
$isModule = $em->getRepository(User::class)->userHasModule($user, $module);
if($isModule and $module->getIsLive() == 1) {
$moduleId = $module->getModuleId();
$modules[$moduleId] = $module;
}
}
}
$headerData = array();
$headerData['headerMessage'] = "";
$headerData['user'] = $user;
$headerData['services'] = $services;
$headerData['modules'] = $modules;
//we load services list of the server into session
if(!empty($session->get('server')) && (empty($session->get('server')->getServices()) || count($session->get('server')->getServices())==0)) {
$server = $em->getRepository(Server::class)->getServer($session->get('server')->getServerId());
foreach($server->getServices() as $service) {
if($service->getIsLive() == 1) {
$session->get('server')->addService($service);
}
/*
print('<hr>QQW session service: ');
\Doctrine\Common\Util\Debug::dump($service);
*/
}
}
return $headerData;
}
public function getSeoData(Request $request)
{
$session = $request->getSession();
$seoData = array();
$seoData['seoTitle'] = "SEO Title";
// print('<hr>QQW SERVER HEADER: ');
// \Doctrine\Common\Util\Debug::dump($session->get('server')->getServices());
return $seoData;
}
public function checkUserEntities(Request $request)
{
$session = $request->getSession();
$em = $this->doctrine->getManager();
//print("<br>QQW checkUserEntities:");
/* temporary setting - we generate always entity */
$this->generateUserEntities();
/* we check user entities */
if(empty($session->get('user')->getDateEntitiesUpdated())) {
$this->generateUserEntities();
$dateTimeNow = new \DateTime("now");
/* we set entity update date in session */
$session->get('user')->setDateEntitiesUpdated($dateTimeNow);
/* we set entity update date in db */
$userId = $session->get('user')->getUserId();
$user = $em->getRepository(User::class)->getUser($userId);
$user->setDateEntitiesUpdated($dateTimeNow);
$em->flush();
}
}
/**
* @throws \Exception
*/
public function generateUserEntities()
{
//define('STDIN',fopen("php://stdin","r"));
if (!defined('STDIN')) define('STDIN',fopen("php://stdin","r"));
/* we generate entities for the user */
// print("<br>Generate entities for the user.");
$dem = $this->doctrine->getManager('dynamic_em');
$application = new Application($this->appKernel);
$application->setAutoExit(false);
// Update schema
//$options = array('command' => 'doctrine:schema:update','--force' => true, '--em' => 'dynamic_em');
//$options = array('command' => 'doctrine:migrations:migrate', '--em' => 'dynamic_em');
//$options = array('command' => 'doctrine:migrations:migrate --em=dynamic_em');
$input = new ArrayInput(array(
'command' => 'doctrine:migrations:migrate',
'--em' => 'dynamic_em'
));
$output = new BufferedOutput();
$application->run($input, $output);
// return the output, don't use if you used NullOutput()
$content = $output->fetch();
//print(" ... Entities generated.");
// \Doctrine\Common\Util\Debug::dump($output);
// return new Response(""), if you used NullOutput()
return new Response($content);
//$options = array('command' => 'symfony server:stop');
//$output = $application->run(new ArrayInput($options));
// print("<br>Entities generated.");
// \Doctrine\Common\Util\Debug::dump($output);
return true;
}
public function checkUserDB(Request $request)
{
$session = $request->getSession();
$em = $this->doctrine->getManager();
$currentUserId = $session->get('user')->getUserId();
if(!$em->getRepository(User::class)->isUserDB($currentUserId)) {
$this->createUserDB($request);
$this->addFlash('notice', 'User database was created.');
return false;
} else {
return true;
}
}
public function createUserDB(Request $request)
{
$session = $request->getSession();
$currentUserId = $session->get('user')->getUserId();
/* we create users db */
$em = $this->doctrine->getManager();
$currentUser = $em->getRepository(User::class)->getUser($currentUserId);
$userDbName = "am_".$currentUser->getUserName();
$em->getRepository(User::class)->createUserDB($currentUserId, $userDbName);
/* we insert db connection to user entity */
$currentUser->setDatabaseName($userDbName);
$currentUser->setDatabaseUser($this->databaseUser);
$currentUser->setDatabasePassword($this->databasePassword);
$session->get('user')->setDatabaseName($userDbName);
$session->get('user')->setDatabaseUser($this->databaseUser);
$session->get('user')->setDatabasePassword($this->databasePassword);
/* we persist and save user */
//$em->persist($user);
$em->flush();
return true;
}
public function isUserFolder(Request $request)
{
$session = $request->getSession();
$currentUserName = $session->get('user')->getUserName();
$imageDir = "../public/users/".$currentUserName;
//print('<br>QQW check image dir: '.$imageDir);
if (is_dir($imageDir)) {
return true;
} else{
return false;
}
}
public function createUserFolder(Request $request)
{
$session = $request->getSession();
$currentUserName = $session->get('user')->getUserName();
$userDir = "../public/users/".$currentUserName;
$imageDir = "../public/users/".$currentUserName."/images";
//print('<br>Create image dir: '.$imageDir);
if (false === mkdir($userDir, 0777, true) OR false === mkdir($imageDir, 0777, true)) {
print('<br>Image dir: '.sprintf('Unable to create the "%s" directory', $imageDir));
//throw new FileException(sprintf('Unable to create the "%s" directory', $imageDir));
return false;
} elseif (!is_writable($imageDir)) {
print('<br>Image dir: '.sprintf('Unable to write in the "%s" directory', $imageDir));
//throw new FileException(sprintf('Unable to write in the "%s" directory', $imageDir));
return false;
} else{
return true;
}
}
public function isUserCustomFolder(Request $request, $folderName)
{
$session = $request->getSession();
$currentUserName = $session->get('user')->getUserName();
$customDir = "../public/users/".$currentUserName."/".$folderName;
//print('<br>QQW check custom dir: '.$customDir);
if (is_dir($customDir)) {
return true;
} else{
return false;
}
}
public function createUserCustomFolder(Request $request, $folderName)
{
$session = $request->getSession();
$currentUserName = $session->get('user')->getUserName();
$userDir = "../public/users/".$currentUserName;
$customDir = "../public/users/".$currentUserName."/".$folderName;
print('<br>Create customDir dir: '.$customDir);
if (false === mkdir($customDir, 0777, true)) {
print('<br>Custom dir: '.sprintf('Unable to create the "%s" directory', $customDir));
//throw new FileException(sprintf('Unable to create the "%s" directory', $customDir));
return false;
} elseif (!is_writable($customDir)) {
print('<br>Custom dir: '.sprintf('Unable to write in the "%s" directory', $customDir));
//throw new FileException(sprintf('Unable to write in the "%s" directory', $customDir));
return false;
} else{
return true;
}
}
public function getUserFolderPaths(Request $request, $userName = '')
{
$userFolderPaths = array();
$session = $request->getSession();
if(!empty($session->get('user'))) {
$currentUserName = $session->get('user')->getUserName();
} else {
$currentUserName = $userName;
}
$userFolderPaths['user'] = "../public/users/".$currentUserName;
$userFolderPaths['images'] = "../public/users/".$currentUserName."/images";
if($_SERVER['HTTP_HOST'] != 'localhost') {
$userFolderPaths['web'] = "http://".$_SERVER['HTTP_HOST']."/users/".$currentUserName;
$userFolderPaths['webroot'] = "http://".$_SERVER['HTTP_HOST'];
} else {
$userFolderPaths['web'] = "https://".$_SERVER['HTTP_HOST']."/users/".$currentUserName;
$userFolderPaths['webroot'] = "https://".$_SERVER['HTTP_HOST']."/";
}
//print('<br>qqw web path: '.$userFolderPaths['web']);
return $userFolderPaths;
}
public function getUserFolderPathsFromUserId($userId)
{
$userFolderPaths = array();
/* we create users db */
$em = $this->doctrine->getManager();
$user = $em->getRepository(User::class)->getUser($userId);
$currentUserName = $user->getUserName();
$userFolderPaths['user'] = "../public/users/".$currentUserName;
$userFolderPaths['images'] = "../public/users/".$currentUserName."/images";
if($_SERVER['HTTP_HOST'] != 'localhost') {
$userFolderPaths['web'] = "http://".$_SERVER['HTTP_HOST']."/users/".$currentUserName;
$userFolderPaths['webroot'] = "http://".$_SERVER['HTTP_HOST'];
} else {
$userFolderPaths['web'] = "https://"."www.".$_SERVER['HTTP_HOST']."/alliancemarkets2/public/users/".$currentUserName;
$userFolderPaths['webroot'] = "https://"."www.".$_SERVER['HTTP_HOST']."/alliancemarkets2/";
}
//print('<br>qqw web path: '.$userFolderPaths['web']);
return $userFolderPaths;
}
function parseContent(Request $request, $text2Parse) {
$left = 0;
//find first left bracket
$left = strpos($text2Parse, '{');
//find first right bracket
$right = strpos($text2Parse, '}');
//print("<br>qqw parse element: ");
$parsedText = "";
if($right>0)
{
$parseElement = substr($text2Parse, $left+1, $right-$left-1);
$textType = explode('_', $parseElement);
if(!empty($textType[1])) {
$elementId = $textType[1];
}
switch($textType[0])
{
case "SLIDESHOW":
//we generate the code for the slideshow
$startText = substr($text2Parse, 0, $right+1);
print('<br>QQW SLIDESHOW');
//$parsedText = ereg_replace ('{'.$parseElement.'}', $this->getSlideShow($textType[1]), $startText);
break; //case "SLIDESHOW":
case "INTERACTIVESLIDESHOW":
//print('<br>INTERACTIVESLIDESHOW');
$startText = substr($text2Parse, 0, $right+1);
$startTextParsed = preg_replace ("{{".$parseElement."}}", $this->getInteractiveSlideShow($elementId), $text2Parse);
$restContent = substr($text2Parse, $right+1, strlen($text2Parse)-$right);
$restContentParsed = $this->parseContent($request, $restContent);
$parsedText = $startTextParsed.$restContentParsed;
break; //case "INTERACTIVESLIDESHOW":
case "REDACTIONLIST":
$startText = substr($text2Parse, 0, $right+1);
$startTextParsed = preg_replace ("{{".$parseElement."}}", $this->getRedactionList($request, $elementId), $startText);
$restContent = substr($text2Parse, $right+1, strlen($text2Parse)-$right);
$restContentParsed = $this->parseContent($request, $restContent);
$parsedText = $startTextParsed.$restContentParsed;
break; //case "REDACTIONLIST":
case "PRODUCTSELECTIONGUIDE":
$startText = substr($text2Parse, 0, $right+1);
$startTextParsed = preg_replace ("{{".$parseElement."}}", $this->getProductSelectionGuide($elementId), $startText);
$restContent = substr($text2Parse, $right+1, strlen($text2Parse)-$right);
$restContentParsed = $this->parseContent($request, $restContent);
$parsedText = $startTextParsed.$restContentParsed;
break; //case "PRODUCTSELECTIONGUIDE":
case "PRODUCTGROUP":
//print('<br>PRODUCTGROUP');
$startText = substr($text2Parse, 0, $right+1);
$startTextParsed = preg_replace ("{{".$parseElement."}}", $this->getProductGroup($elementId, $request), $startText);
$restContent = substr($text2Parse, $right+1, strlen($text2Parse)-$right);
$restContentParsed = $this->parseContent($request, $restContent);
$parsedText = $startTextParsed.$restContentParsed;
break; //case "PRODUCTGROUP":
case "WEBGALLERIES":
//print('<br>qqw WEBGALLERIES');
$startText = substr($text2Parse, 0, $right+1);
$startTextParsed = preg_replace ("{{".$parseElement."}}", $this->getWebGalleries($elementId, $request), $startText);
$restContent = substr($text2Parse, $right+1, strlen($text2Parse)-$right);
$restContentParsed = $this->parseContent($request, $restContent);
$parsedText = $startTextParsed.$restContentParsed;
break; //case "WEBGALLERIES":
case "GALLERY3D":
//print('<br>qqw GALLERY3D');
$startText = substr($text2Parse, 0, $right+1);
$startTextParsed = preg_replace ("{{".$parseElement."}}", $this->getGallery3D($elementId, $request), $startText);
$restContent = substr($text2Parse, $right+1, strlen($text2Parse)-$right);
$restContentParsed = $this->parseContent($request, $restContent);
$parsedText = $startTextParsed.$restContentParsed;
break; //case "GALLERY3D":
}
//we try to search in the rest of the content
$restContent = substr($text2Parse, $right+1, strlen($text2Parse)-$right);
//print('<br><br><b>RESTCONTENT:</b> '.htmlentities($restContent));
//$parsedText .= $this->parseContent($request, $restContent);
}
if($parsedText == '') $parsedText = $text2Parse;
return $parsedText;
}
function getRedactionList(Request $request, $redactionListId) {
$session = $request->getSession();
$listContent = '';
/* we load entity managers */
$em = $this->doctrine->getManager();
$dem = $this->doctrine->getManager('dynamic_em');
// we get the redaction list
$redactionList = $dem->getRepository(RedactionList::class)->getRedactionList($redactionListId);
if(empty($redactionList)) {
return $listContent;
}
// we get the user info
$user = $em->getRepository(User::class)->getUser($redactionList->getUserId());
$userDirs = $this->getUserFolderPathsFromUserId($redactionList->getUserId());
if(!empty($redactionList->getCssClass())) {
$cssClass = $redactionList->getCssClass();
} else {
$cssClass = '';
}
$webPages = [];
foreach($redactionList->getWebPages() as $webPage) {
$webPages[] = $webPage;
}
foreach(array_reverse($webPages) as $webPage) {
$listContent .= '<div class="'.$cssClass.'redactionListPage">';
$listContent .= '<div class="'.$cssClass.'redactionListThumb">';
//print('<br>QQW webPage: ');
//\Doctrine\Common\Util\Debug::dump($webPage);
//print('<br>QQW session langKey: '.$session->get('lang')->getLangKey());
$webPage->setLocale($session->get('lang')->getLangKey());
$dem->refresh($webPage);
$pageContent = $webPage->getWebPageContent();
//print('<hr>QQW webPage 2: ');
//\Doctrine\Common\Util\Debug::dump($webPage);
$webPageLink = $userDirs['webroot'].'/web/'.$webPage->getWebsiteId().'/page/'.$webPage->getWebPageId();
if(!empty($webPage->getImageFile())) {
//$imagePath = 'users/'.$user->getUserName().'/images/'.$webPage->getImageFile();
$imagePath = $userDirs['web'].'/images/'.$webPage->getImageFile();
if(!empty($redactionList->getThumbWidth())) {
$imageWidth = $redactionList->getThumbWidth();
} else {
$imageWidth = 200;
}
//$listContent .= 'QQW THUMB: '.$imagePath.'</div>';
$listContent .= '<a href="'.$webPageLink.'">';
$listContent .= '<img src="'.$imagePath.'" width="'.$imageWidth.'" class="'.$redactionList->getThumbWidth().'">';
$listContent .= '</a>';
}
$listContent .= '</div>';
$listContent .= '<div class="'.$cssClass.'redactionListText">';
$listContent .= '<a href="'.$webPageLink.'" class="'.$cssClass.'redactionListLink">'.$webPage->getWebPageName().'</a>';
$listContent .= '<div class="'.$cssClass.'redactionListDescription">'.$webPage->getWebPageDescription().'</div>';
$listContent .= '</div>';
$listContent .= '</div>';
}
return $listContent;
}
function getProductSelectionGuide($guideId) {
/* we load entity managers */
$em = $this->doctrine->getManager();
$dem = $this->doctrine->getManager('dynamic_em');
$content = '';
//print('<hr>qqw Product Selection Guide ');
/* we get the selection guide */
$guide = $dem->getRepository(ProductSelectionGuide::class)->getProductSelectionGuide($guideId);
/* we get product selection guide steps*/
$productSelectionStepList = $dem->getRepository(ProductSelectionStep::class)->getProductSelectionStepListByGuide($guide);
/* we get the user info */
$user = $em->getRepository(User::class)->getUser($guide->getUserId());
$count = 0;
$content .= '<div class="productSelectionGuide">';
/* we display selection steps */
foreach($productSelectionStepList as $step) {
$count++;
$content .= '<div class="productSelectionStep">';
$content .= '<div class="productSelectionStepTitle">';
$content .= $step->getProductSelectionStepName();
$content .= '</div>';
$content .= '<div class="productSelectionStepContent">';
/* we display parameters */
foreach($step->getParameters() as $parameter) {
$content .= '<div class="productSelectionParameter">';
$paramName = 'param_'.$parameter->getProductParameterId();
if($parameter->getParameterType() == 1) {
/* we display choices */
$choices = $parameter->getProductParameterChoices();
$pChoices = explode(";", $parameter->getProductParameterChoices());
$choiceCount = 0;
foreach($pChoices as $choice) {
$choiceCount++;
$content .= '<label for="'.$paramName.'_'.$choiceCount.'" class="guideChoice"><input type="radio" name="'.$paramName.'" id="'.$paramName.'_'.$choiceCount.'" value="'.trim($choice).'"><span class="guideChoiceTitle">'.trim($choice).'</span></label>';
}
} else {
/* we display checkboxes */
//$content .= $parameter->getProductParameterName();
$content .= '<label for="'.$paramName.'" class="guideChoice"><input type="checkbox" name="'.$paramName.'" id="'.$paramName.'" value="1"><span class="guideChoiceTitle">'.$parameter->getProductParameterName().'</span></label>';
}
$content .= '</div>';
}
$content .= '</div>';
$content .= '</div>';
}
$content .= '</div>';
return $content;
}
function getProductGroup($groupId, Request $request) {
/* we load session data */
//parent::init($request);
$session = $request->getSession();
/* we load entity managers */
$em = $this->doctrine->getManager();
$dem = $this->doctrine->getManager('dynamic_em');
$eshopId = null;
$content = '';
$userDirs = $this->getUserFolderPaths($request);
/* we get the product group */
$group = $dem->getRepository(ProductGroup::class)->getProductGroup($groupId);
/* we get products */
$productCollection = $dem->getRepository(Product::class)->getProductListByGroup($group);
//print('<br>qqw request: ');
//\Doctrine\Common\Util\Debug::dump($request);
$productThumbs = array();
foreach($productCollection as $product) {
$pId = $product->getProductId();
if(empty($eshopId)) {
$eshopId = $dem->getRepository(Product::class)->getEshopByProduct($product->getProductId());
if(empty($eshopId)) {
//we get ehop id from url
$pathArray = explode("/", $request->getPathInfo());
$eshopId = $pathArray[2];
}
$eshop = $em->getRepository(Eshop::class)->getEshop($eshopId);
$user = $em->getRepository(User::class)->getUser($eshop->getUserId());
}
if($product->getImage1() != "") {
if (strpos($product->getImage1(), 'http') === false) {
$imagePath = 'users/'.$user->getUserName().'/images/'.$product->getImage1();
$imageThumbPath = 'users/'.$user->getUserName().'/images/thumb_'.$product->getImage1();
} else {
$imagePath = $product->getImage1();
$path = parse_url($imagePath, PHP_URL_PATH);
$imageThumbPath = 'users/'.$user->getUserName().'/images/thumb_'.basename($path);
}
/*
print('<br>qqw imagePath: '.$imagePath);
print('<br>qqw imageThumbPath: '.$imageThumbPath);
*/
$imageThumb = $this->getEshopImageThumb($eshop, $imagePath, $imageThumbPath);
$productThumbs[$pId] = $imageThumb;
}
}
$content .= '<div class="productGroup">';
foreach($productCollection as $product) {
if(empty($eshopId)) {
$eshopId = $dem->getRepository(Product::class)->getEshopByProduct($product->getProductId());
$eshop = $em->getRepository(Eshop::class)->getEshop($eshopId);
$user = $em->getRepository(User::class)->getUser($eshop->getUserId());
}
/* we setup product names - if empty then we load multilingual values */
$productName = '';
if(!empty($product->getProductName()) && $product->getProductName() != '') {
$productName = $product->getProductName();
} else {
//we try to get the product name from multilangual fields
foreach($eshop->getLanguages() as $lang) {
$product->setLocale($lang->getLangKey());
$dem->refresh($product);
if(!empty($product->getProductName()) && $product->getProductName() != '') {
$productName = $product->getProductName();
}
}
}
$product->setProductName($productName);
/*
print('<br>qqw eshopId: ');
\Doctrine\Common\Util\Debug::dump($eshopId);
*/
$productLink = $userDirs['webroot'].'/eshop/'.$eshopId.'/product/'.$product->getProductId();
/* we get price(s) to display */
$displayPrice = null;
$productIds = array();
$productIds[] = $product->getProductId();
/* we load prices */
$productPriceList = $dem->getRepository(Product::class)->getProductPriceList($productIds);
$priceLevelList = $dem->getRepository(PriceLevel::class)->getPriceLevelList();
$defaultCurrency = $em->getRepository(Currency::class)->getCurrency($eshop->getPreferredCurrencyId());
$targetCurrency = $session->get('eshopCurrency');
/* we load currency rated prices */
$productPriceList = $dem->getRepository(Product::class)->getCurrencyRatedProductPriceList($productPriceList, $defaultCurrency, $targetCurrency);
$displayPrice = null;
$stoneShopPrice = null;
foreach($productPriceList as $price) {
if($price->getProductId() == $product->getProductId()) {
/* we get default price level */
/* we get price level according to logged contact-customer */
if(!empty($session->get('contact')) && !empty($session->get('contact')->getPriceLevel()) && $price->getPriceLevelId()==$session->get('contact')->getPriceLevel()->getPriceLevelId()) {
/* we get netto or brutto value according to e-shop configuration */
if(!empty($eshop->isDisplayNettoPrices()) && $eshop->isDisplayNettoPrices()==true) {
$displayPrice = round($price->getNettoValue(),$eshop->getRoundPrice());
} else {
$displayPrice = round($price->getBruttoValue(),$eshop->getRoundPrice());
}
if(!empty($eshop->isDisplayNettoPrices()) && $eshop->isDisplayNettoPrices()==true) {
//$displayPriceVAT = $displayPrice + ($displayPrice * ($productVAT/100));
//$displayPriceVATLabel = $this->translator->trans('product.price_with_VAT');
} else {
//$displayPriceVAT = $displayPrice - ($displayPrice * ($productVAT/100));
//$displayPriceVATLabel = $this->translator->trans('product.price_without_VAT');
}
} elseif($price->getPriceLevelId() == 1) {
/* we get netto or brutto value according to e-shop configuration */
if(!empty($eshop->isDisplayNettoPrices()) && $eshop->isDisplayNettoPrices()==true) {
$displayPrice = round($price->getNettoValue(),$eshop->getRoundPrice());
$stoneShopPrice = round($price->getNettoValue(),$eshop->getRoundPrice());
} else {
$displayPrice = round($price->getBruttoValue(),$eshop->getRoundPrice());
$stoneShopPrice = round($price->getBruttoValue(),$eshop->getRoundPrice());
}
} elseif ($price->getPriceLevelId() > 1) {
foreach($priceLevelList as $priceLevel) {
if($price->getPriceLevelId() == $priceLevel->getPriceLevelId() && $priceLevel->getPriceLevelName() == "stoneshop") {
if(!empty($eshop->isDisplayNettoPrices()) && $eshop->isDisplayNettoPrices()==true) {
$stoneShopPrice = round($price->getNettoValue(),$eshop->getRoundPrice());
} else {
$stoneShopPrice = round($price->getBruttoValue(),$eshop->getRoundPrice());
}
}
}
}
}
}
//$displayPrice = 22;
$content .= $this->renderView('eshopProduct_GRID.html.twig',
array('product' => $product,
'eshop' => $eshop,
'displayPrice' => $displayPrice,
'stoneShopPrice' => $stoneShopPrice,
'productThumbs' => $productThumbs,
'userDirs' => $userDirs,
'user' => $user)
);
}
$content .= '</div>';
/*
print('<hr>qqw content: ');
\Doctrine\Common\Util\Debug::dump($content);
print('<hr>');
*/
return $content;
}
function getWebGalleries($webId, Request $request) {
/* we load entity managers */
$em = $this->doctrine->getManager();
$dem = $this->doctrine->getManager('dynamic_em');
//$rootDir = $this->container->get('kernel')->getRootDir();
/* we get current web */
$web = $em->getRepository(Website::class)->getWebsite($webId);
$userDirs = $this->getUserFolderPathsFromUserId($web->getUserId());
$eshopId = null;
$content = '';
/* we get list of galleries */
$galleryList = $dem->getRepository(Gallery::class)->getWebGalleryList($webId);
//print('<br>qqw current webpage: '.$request->getUri());
/*
\Doctrine\Common\Util\Debug::dump($productCollection);
*/
$content .= '<div class="galleryList">';
foreach($galleryList as $gallery) {
$content .= '<div class="galleryPanel">';
if(!empty($gallery->getGalleryLogoUrl())) {
$content .= '<a href="'.$userDirs['webroot'].'/public/'.$web->getWebsiteId().'/gallery/'.$gallery->getGalleryId().'?backUrl='.$request->getUri().'"><img src="'.$gallery->getGalleryLogoUrl().'" alt="Gallery Logo" border="0" width="200"></a>';
}
$content .= '<div class="galleryDescription">';
$content .= '<a href="'.$userDirs['webroot'].'/public/'. $webId.'/gallery/'.$gallery->getGalleryId().'?backUrl='.$request->getUri().'" class="galleryTitle">'.$gallery->getGalleryName().'</a>';
$content .= $gallery->getGalleryDescription();
$content .= '</div>';
$content .= '</div>';
}
$content .= '</div>';
return $content;
}
function getInteractiveSlideShow($galleryId) {
/* we load entity managers */
$em = $this->doctrine->getManager();
$dem = $this->doctrine->getManager('dynamic_em');
/* we get the gallery info */
$gallery = $dem->getRepository(Gallery::class)->getGallery($galleryId);
$galleryItemCollection = $dem->getRepository(GalleryItem::class)->getGalleryItemList($galleryId);
$userDirs = $this->getUserFolderPathsFromUserId($gallery->getUserId());
/*
print('<br>qqw getInteractiveSlideShow: ');
\Doctrine\Common\Util\Debug::dump($gallery);
*/
$sWidth = $gallery->getSlideshowWidth();
$sHeight = $gallery->getSlideshowHeight();
$sCount = 0;
$navPanel = '';
$slideShow = '<div class="slideshowPanel">';
$slideShow .= '<div id="slideshow" style="z-index:1;" class="slideshow">';
foreach($galleryItemCollection as $galleryItem) {
/*
print('<br>qqw galleryItem: ');
\Doctrine\Common\Util\Debug::dump($galleryItem);
*/
/*
if(strpos($row['title'],"ttp://")>0) $img = $row['title'];
else $img = './users/'.$userName.'/gallery/'.rawurlencode($galleryName).'/'.$row['title'];
*/
$img = $userDirs['web']."/images/".$galleryItem->getGalleryItemFile();
//$webPath = $userDirs['web']."/images/".$galleryItem->getGalleryItemFile();
if($sCount == 0)
{
$slideShow .= '<div class="active" id="slide_'.$sCount.'">';
if($galleryItem->getClickURL()!='') $slideShow .= '<a href="'.$galleryItem->getClickURL().'">';
$slideShow .= '<img src="'.$img.'" alt="Slideshow Image '.$sCount.'" class="slideshowImage" border="0" />';
if($galleryItem->getClickURL()!='') $slideShow .= '</a>';
$slideShow .= '</div>';
}
else
{
$slideShow .= '<div id="slide_'.$sCount.'">';
if($galleryItem->getClickURL()!='') $slideShow .= '<a href="'.$galleryItem->getClickURL().'">';
$slideShow .= '<img src="'.$img.'" alt="Slideshow Image '.$sCount.'" class="slideshowImage" border="0" />';
if($galleryItem->getClickURL()!='') $slideShow .= '</a>';
$slideShow .= '</div>';
}
if($galleryItem->getGalleryItemName()!='') $countLabel = $galleryItem->getGalleryItemName();
else $countLabel = $sCount + 1;
//if($sCount > 0) $navPanel .= '';
$navPanel .= '<span id="slideNumber_'.$sCount.'" class="slideNumber"><a href="javascript:void(0)" onclick="viewFadeSlide('.$sCount.', '.count($galleryItemCollection).')" class="slideLink">'.$countLabel.'</a></span>';
$sCount++;
}
$slideShow .= '</div>';
$slideShow .= '</div>';
$slideShow .= '<div class="slideMenu">'.$navPanel.'</div>';
//$slideShow .= '<table border="0" cellpadding="0" cellspacing="0" align="center"><tr><td align="center" valign="top" class="slideLabelTable">'.$navPanel.'</td></tr></table>';
return $slideShow;
}
function getGallery3D($gallery3DId, Request $request) {
/* we load session data */
//parent::init($request);
$session = $request->getSession();
// we load entity managers
$em = $this->doctrine->getManager();
$dem = $this->doctrine->getManager('dynamic_em');
$content = '';
// we get the gallery
$gallery3D = $dem->getRepository(Gallery3D::class)->getGallery3D($gallery3DId);
$user = $em->getRepository(User::class)->getUser($gallery3D->getUserId());
$userDirs = $this->getUserFolderPaths($request, $user->getUserName());
$logger = $this->getLogger(null, 'gallery 3D: '.$gallery3DId);
//print('<br>gallery3D: ');
//\Doctrine\Common\Util\Debug::dump($gallery3D);
// we get parent gallery items
$galleryItemCollection = null;
if(!empty($gallery3D->getGallery())) {
$galId = $gallery3D->getGallery()->getGalleryId();
$galleryItemCollection = $dem->getRepository(GalleryItem::class)->getGalleryItemList($galId);
}
// we get parent gallery items
$textureItemCollection = null;
if(!empty($gallery3D->getTextureGallery())) {
$galId = $gallery3D->getTextureGallery()->getGalleryId();
$textureItemCollection = $dem->getRepository(GalleryItem::class)->getGalleryItemList($galId);
}
// print('<br>user: ');
// \Doctrine\Common\Util\Debug::dump($user);
// print('<br>QQW freeWorld 22');
// \Doctrine\Common\Util\Debug::dump($gallery3D->getFreeWorlds());
$content .= '<div class="gallery3DPanel">';
$template3D = 'gallery3D/gallery3D.html.twig';
if(!empty($gallery3D->getTemplate3DPath())) {
$template3D = 'gallery3D/'.$gallery3D->getTemplate3DPath();
}
//print('<hr>qqw template3D: '.$template3D);
$content .= $this->renderView($template3D,
array('gallery3D' => $gallery3D,
'user' => $user,
'userDirs' => $userDirs,
'logger' => $logger,
'galleryItemCollection' => $galleryItemCollection,
'textureItemCollection' => $textureItemCollection,
'isHeader' => false,
'isFullscreen' => false,
)
);
$content .= '</div>';
/*
print('<hr>qqw content: ');
\Doctrine\Common\Util\Debug::dump($content);
print('<hr>');
*/
return $content;
}
function GetImage($path) {
//$mime = mime_content_type($path);
$mime = @exif_imagetype($path);
//print('<br>qqw mime: '.$mime);
switch($mime) {
case 'IMAGETYPE_PNG':
case 3:
$img = imagecreatefrompng($path);
break;
case 'IMAGETYPE_GIF':
case 1:
$img = imagecreatefromgif($path);
break;
case 'IMAGETYPE_JPEG':
case 2:
$img = imagecreatefromjpeg($path);
break;
case 'IMAGETYPE_BMP':
case 6:
$img = imagecreatefrombmp($path);
break;
default:
$img = null;
}
/*
print('<br>qqw img: ');
\Doctrine\Common\Util\Debug::dump($img);
*/
return $img;
}
function analyseImageFromText($text="", $maxCharacterRow=50) {
$analysedText = array();
return $analysedText;
}
function getImageFromText($text="", $colorType="default", $imagePath, $imageWebPath, $countCharactersInLine = 30, $imageName="image_name", $imageWidth=400, $imageHeight=60, $fontSize=40, $positionY = 40) {
/* Set the content-type */
//header('Content-type: image/png');
$newText = wordwrap($text, $countCharactersInLine, "\n", false);
$arrayText = explode("\n", $newText);
$rowCount = count($arrayText);
//print('<br>QQW rowcount: '.$rowCount);
//print('<br>QQW new image text: '.$newText);
//print('<br>QQW imageWidth: '.$imageWidth);
//print('<br>QQW imageHeight: '.$imageHeight);
if($rowCount > 0) {
$imageHeight = $imageHeight * $rowCount;
}
/* Create the image */
$im = imagecreatetruecolor($imageWidth, $imageHeight);
/* Create some colors */
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$silver = imagecolorallocate($im, 177, 177, 177);
$black = imagecolorallocate($im, 0, 0, 0);
$green = imagecolorallocate($im, 0, 255, 0);
$yellow = imagecolorallocate($im, 255, 255, 0);
$orange = imagecolorallocate($im, 255, 150, 0);
switch ($colorType) {
case "default":
$bgColor = $black;
$textColor = $yellow;
break;
case "silver-black":
$bgColor = $silver;
$textColor = $black;
break;
case "black-yellow":
$bgColor = $black;
$textColor = $yellow;
break;
case "black-white":
$bgColor = $white;
$textColor = $black;
break;
case "black-green":
$bgColor = $black;
$textColor = $green;
break;
case "orange-black":
$bgColor = $black;
$textColor = $orange;
break;
}
imagefilledrectangle($im, 0, 0, ($imageWidth-1), ($imageHeight-1), $bgColor);
/* font path */
//$font = 'arial.ttf';
//$font = "../web/ArialBold.ttf";
// $font = $this->get('kernel')->getRootDir().'/public/ArialBold.ttf';
$font = $this->appKernel->getProjectDir() . '/public/ArialBold.ttf';
//$font = "ArialBold.ttf";
//$font = "http://localhost/alliancemarkets2/web/ArialBold.ttf";
/* Add some shadow to the text */
//imagettftext($im, 40, 0, 40, 50, $black, $font, $text);
/* Add the text */
//$positionY = 30;
foreach($arrayText as $key => $rowText) {
//print('<br>QQW new text row: '.$rowText);
imagettftext($im, $fontSize, 0, 15, $positionY, $textColor, $font, $rowText);
$positionY += 25;
}
/* Using imagepng() results in clearer text compared with imagejpeg() */
$file = $imagePath."/".$imageName.".png";
$fileWeb = $imageWebPath."/".$imageName.".png";
imagepng($im, $file);
//imagejpeg($im, $file);
imagedestroy($im);
return $fileWeb;
}
function getNormalisedText($text="") {
$text = str_replace(' ', '', $text);
$text = str_replace('.', '', $text);
$text = str_replace("'", "", $text);
return $text;
}
function getEshopImageThumb($eshop, $imagePath, $imageThumbPath, $isCategoryThumb = false, $category = null) {
if(!is_file($imageThumbPath)) {
//$imageData = getimagesize($imagePath);
list($width, $height) = @getimagesize($imagePath);
if($width > 0)
{
$imageData2 = array('h' => $height, 'w' => $width );
if(!empty($isCategoryThumb) && $isCategoryThumb) {
//getEshopImageThumb
if(!empty($eshop->getCategoryImageThumbWidth()) && $eshop->getCategoryImageThumbWidth() > 0) {
$thumbWidth = $eshop->getCategoryImageThumbWidth();
} else {
$thumbWidth = 150;
}
} elseif(!empty($category) && !empty($category->getImageThumbWidth()) && $category->getImageThumbWidth() > 0) {
$thumbWidth = $category->getImageThumbWidth();
} else {
$thumbWidth = $eshop->getImageThumbWidth();
}
if($imageData2['w'] == 0) $imageData2['w'] = 1;
$thumbHeight = ($imageData2['h']/$imageData2['w'])*$thumbWidth;
if(!empty($category) && !empty($category->getImageThumbHeight()) && $category->getImageThumbHeight() > 0) {
$eshopThumbHeight = $category->getImageThumbWidth();
} elseif($eshop->getImageThumbHeight() > 0) {
$eshopThumbHeight = $eshop->getImageThumbHeight();
} else {
$eshopThumbHeight = 200;
}
/* if the thumb height is bigger than allowed thumb height we generate thumb according to height*/
if($thumbHeight > $eshopThumbHeight) {
$thumbHeight = $eshopThumbHeight;
if($imageData2['h'] == 0) $imageData2['h'] = 1;
$thumbWidth = ($imageData2['w']/$imageData2['h'])*$thumbHeight;
}
//print('<br>qqw thumb w: '.$thumbWidth.' h: '.$thumbHeight);
$srcimg = $this->GetImage($imagePath);
$destimg = @imagecreatetruecolor($thumbWidth,$thumbHeight);
/*
print('<br>qqw srcimg: ');
print_r($srcimg);
*/
/*
if(@getimagesize($imagePath)) {
//print('<br>qqw is file: '.$imagePath);
ImageCopyResized($destimg,$srcimg,0,0,0,0,$thumbWidth,$thumbHeight,ImageSX($srcimg),ImageSY($srcimg));
ImageJPEG($destimg,$imageThumbPath, 100);
}
*/
}
}
return $imageThumbPath;
}
function getLogger($user=null, $loggerName = 'universal') {
$logPaths = array();
$rootDir = $this->appKernel->getProjectDir();
//$templatesDir = $this->appKernel->getProjectDir() . '/app/Resources/views';
// $rootDir = $this->container->get('kernel')->getRootDir();
if(!empty($user)) {
/* we get user paths */
//@todo - setting for users
} else {
/* we set logging to universal location */
$logPaths['logPath'] = $rootDir.'/var/log/am2.log';
$logPaths['logErrorPath'] = $rootDir.'/var/log/am2_error.log';
}
/*
print("\n\n qqw logPaths: ");
\Doctrine\Common\Util\Debug::dump($logPaths);
*/
$logger = new Logger($loggerName);
//$log = $this->container->get('logger');
$errorHandler = new ErrorHandler($logger);
$errorHandler->registerErrorHandler([], false);
$errorHandler->registerExceptionHandler();
$errorHandler->registerFatalHandler();
if(!empty($logPaths['logPath'])) {
$logHandler = new StreamHandler($logPaths['logPath'], Logger::NOTICE);
$logger->pushHandler($logHandler);
}
//$logError= new Logger('files');
if(!empty($logPaths['logErrorPath'])) {
$logErrorHandler = new StreamHandler($logPaths['logErrorPath'], Logger::ERROR);
$logger->pushHandler($logErrorHandler);
//$syslogHandler = new SyslogHandler($logPaths['logErrorPath'], 'user');
//$log->pushHandler($syslogHandler);
}
return $logger;
}
function readFileTail($file, $lines) {
//global $fsize;
$handle = fopen($file, "r");
$linecounter = $lines;
$pos = -2;
$beginning = false;
$text = array();
while ($linecounter > 0) {
$t = " ";
while ($t != "\n") {
if(fseek($handle, $pos, SEEK_END) == -1) {
$beginning = true;
break;
}
$t = fgetc($handle);
$pos --;
}
$linecounter --;
if ($beginning) {
rewind($handle);
}
$text[$lines-$linecounter-1] = fgets($handle);
if ($beginning) break;
}
fclose ($handle);
return array_reverse($text);
}
function is_url($url) {
$file_headers = @get_headers($url);
if(!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found') {
return false;
}
else {
return true;
}
}
/**
* Returns generated unique ID.
*
* @return string
*/
public function generateUId()
{
//$this->container
$session = $this->container->get('session');
return substr( $session->getId(), 0, 3 ) . substr( md5( uniqid( '', true ).'|'.microtime() ), 0, 29 );
}
function translate2($from_lan, $to_lan, $text){
$json = json_decode(file_get_contents('https://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=' . urlencode($text) . '&langpair=' . $from_lan . '|' . $to_lan));
$translated_text = $json->responseData->translatedText;
return $translated_text;
}
function translate($from_lan, $to_lan, $text) {
$url = $this->translateBaseUrl . '?key=' . $this->translateApiKey . '&text=' . rawurlencode($text) . '&lang=' . $from_lan . '-' . $to_lan;
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($handle);
$responseDecoded = json_decode($response, true);
curl_close($handle);
//print("<br>QQW responseDecoded: ");
//\Doctrine\Common\Util\Debug::dump($responseDecoded);
if(!empty($responseDecoded['text'])) {
$translated_text = $responseDecoded['text'][0];
} else {
$translated_text = '';
}
return $translated_text;
}
/**
* Checks if any user is logged in admin.
*
* @return string
*/
public function isLoggedUser($request, $loginRedirect = true) {
$this->init($request);
$session = $request->getSession();
if(!empty($session->get('user'))) {
return true;
} else {
return false;
}
}
# get success response from recaptcha and return it to controller
function captchaVerify($recaptcha) {
$url = "https://www.google.com/recaptcha/api/siteverify";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
"secret"=>"6LdD38wZAAAAAPUXf4e2LKQ49KaKKdrrEmKhyAEn","response"=>$recaptcha));
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response);
return $data->success;
}
public function getTotalOrderItemPrice(Request $request, $product, $units, $isPackSaleModule=false)
{
$totalOrderItemPrice = (int)$units * (int)$request->request->get('productPrice');
if($isPackSaleModule) {
/* @todo - product pack price*/
//print("<br>qqw adding to basket pid: ".$product->getProductId());
//print(":: units: ".$units." :: PiecesInPack:".$product->getPiecesInPack());
//print(":: productPrice: ".$request->request->get('productPrice'));
if($product->getPiecesInPack() > 0 && ($units / $product->getPiecesInPack()) > 1) {
//print('<br>... more that 10');
//price for package(s)
$subPrice1 = floor($units / $product->getPiecesInPack()) * $request->request->get('productPackPrice');
//print(' :: subPrice1: '.$subPrice1);
//price for products left by modulo
$subPrice2 = ($units % $product->getPiecesInPack()) * $request->request->get('productPrice');
//print(' :: subPrice2: '.$subPrice2);
$totalOrderItemPrice = $subPrice1 + $subPrice2;
} elseif ($product->getPiecesInPack() > 0 && ($units / $product->getPiecesInPack()) == 1) {
//print('<br>... equals 10');
$totalOrderItemPrice = floor($units / $product->getPiecesInPack()) * $request->request->get('productPackPrice');
} else {
//print('<br>... less that 10');
$totalOrderItemPrice = (int)$units * (int)$request->request->get('productPrice');
}
/*
print(":: productPackPrice: ".$request->request->get('productPackPrice'));
echo ("<br> units mod PiecesInPack: ".($units % $product->getPiecesInPack()));
echo (":: units divided PiecesInPack: ".($units / $product->getPiecesInPack()));
echo (":: floor: ".floor($units / $product->getPiecesInPack()));
*/
}
return $totalOrderItemPrice;
}
public function sendEmail($to, $subject, $from, $body)
{
$user = 'info@virtualrealitycommerce.cz';
$pass = 'S7E3E4j4!f7';
$server = 'smtp.web4u.cz';
//$port = '587';
$port = '465';
// Generate connection configuration
$dsn = "smtp://" . $user . ":" . $pass . "@" . $server . ":" . $port;
$transport = Transport::fromDsn($dsn);
$customMailer = new Mailer($transport);
// Generates the email
$email = (new TemplatedEmail())
->from(new Address('info@virtualrealitycommerce.cz', $subject))
->to($to)
->subject($subject)
->htmlTemplate('emails/email.html.twig')
->context(['body' => $body]);
// IMPORTANT: as you are using a customized mailer instance, you have to make the following
// configuration as indicated in https://github.com/symfony/symfony/issues/35990.
$loader = new FilesystemLoader('../templates/');
$twigEnv = new Environment($loader);
$twigBodyRenderer = new BodyRenderer($twigEnv);
$twigBodyRenderer->render($email);
// Sends the email
try {
$customMailer->send($email);
return true;
} catch (\Exception $e) {
print('<br>email error: ');
print_r($e->getMessage());
return false;
}
}
public function sendEmail2($to, $subject, $from, $body)
{
print('<br>Sending mail...');
$body = 'my email body';
$message = "<html><body><h1>" . "Hi, there 99!" . "</h1></body></html>";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: Info<user@example.com>" . "\r\n";
$status = @mail("webexciter@yahoo.com", "Testing", $message, $headers);
print('<br>mail status:');
print_r($status);
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
$headers .= "From: <{$from}>\r\n";
$headers .= "Reply-To: <{$from}>\r\n";
$headers .= "Subject: {$subject}\r\n";
$headers .= "X-Mailer: PHP/".phpversion()."\r\n";
mail('webexciter@yahoo.com', 'My Subject', 'My Message');
if(mail($to, $subject, $body, $headers)) {
print('<br>Email was sent.');
print('<br>QQW Sending 2');
return true;
} else {
print('<br>Email was not sent.');
print_r(error_get_last());
return false;
}
}
public function sendEmail3($to, $subject, $from, $body)
{
print('<br>Sending Symfony mailer...');
$email = (new Email())
->from('info@virtualrealitycommerce.cz')
//->from($user->getEmail())
->to($to)
//->cc('cc@example.com')
//->bcc('bcc@example.com')
//->replyTo('fabien@example.com')
//->priority(Email::PRIORITY_HIGH)
->subject('Time for Symfony Mailer 101 !')
->text('Sending emails is fun again!')
->html('<p>See Twig integration for better HTML integration!</p>');
try {
$this->mailer->send($email);
//$this->addFlash('notice', $this->translator->trans('user.forgotten_password_sent').': '.$emailAddress);
return true;
} catch (\Exception $e) {
// some error prevented the email sending; display an
// error message or try to resend the message
//$this->addFlash('error', $this->translator->trans('user.forgotten_password_sent_error').': '.$emailAddress);
print_r($e->getMessage());
return false;
}
}
public function sendEmail4($to, $subject, $from, $body)
{
print('<br>Sending cli email...'.$body);
$output = null;
$retval = null;
$body = "<h1>my email title</h1>";
//$command = 'echo "'.addslashes($body).'" | mail -a "Content-type: text/html" -s "'.$subject.'" '.$to;
$command = 'echo "'.$body.'" | mail -s "'.$subject.'" '.$to;
if (exec($command, $output, $retval) === false) {
var_dump($output);
return false;
} else {
return true;
}
}
public function sendEmail5($to, $subject, $from, $body)
{
print('<br>Sending cli email...'.$body);
require_once("Mail.php");
$from = "Your Name <email@blahblah.com>";
$to = "Their Name <webexcietr@yahoo.com>";
$subject = "Subject";
$body = "Lorem ipsum dolor sit amet, consectetur adipiscing elit...";
$host = "mailserver.virtualrealitycommerce.org";
$username = "smtp_username";
$password = "smtp_password";
$headers = array('From' => $from, 'To' => $to, 'Subject' => $subject);
$smtp = Mail::factory('smtp', array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if ( PEAR::isError($mail) ) {
echo("<p>Error sending mail:<br/>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message sent.</p>");
}
}
public function sendAdminEmail($subject, $from, $body)
{
//print('<br>Sending admin email...');
//sends email to owner
$message = (new \Swift_Message($subject))
->setFrom($from)
->setTo('easycommerc@gmail.com')
->setBody($body,'text/plain')
;
$this->get('mailer')->send($message);
$this->addFlash('notice', 'Email was sent to administrators.');
}
public function adminMainMenu(Request $request)
{
$menuItems = array(0 => array('link' => 'homeuser', 'langKey' => 'user.admin', 'routeName' => 'homeuser'),
1 => array('link' => 'eshopAdmin', 'langKey' => 'eshop.admin', 'routeName' => 'eshopAdmin'),
2 => array('link' => 'orderlist', 'langKey' => 'eshop.orders', 'routeName' => 'orderList'),
3 => array('link' => 'productedit', 'langKey' => 'eshop.products', 'routeName' => 'productListEdit'),
4 => array('link' => 'productnew', 'langKey' => 'eshop.new_product', 'routeName' => 'productNew'),
5 => array('link' => 'categories', 'langKey' => 'eshop.categories', 'routeName' => 'categories'),
6 => array('link' => 'categorynew', 'langKey' => 'eshop.new_category', 'routeName' => 'categoryNew'),
7 => array('link' => 'contacts', 'langKey' => 'knowledgebase.contacts', 'routeName' => 'contacts'),
8 => array('link' => 'eshopnew', 'langKey' => 'eshop.new_eshop', 'routeName' => 'eshopNew'),
9 => array('link' => 'eshopConfig', 'langKey' => 'eshop.config', 'routeName' => 'eshopConfig'),
);
return $menuItems;
}
}