<?php
namespace App\Package\Openform\Tools\FrontUtil;
use App\Package\Openform\Entity\Page;
use App\Package\Openform\Entity\Config;
use Doctrine\ORM\EntityManagerInterface;
use App\Package\Openform\Entity\PageSection;
// use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
// use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
// use App\Package\Toolkit\Exception\Exception\Exception;
use App\Package\Openform\Entity\GalleryImage;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use App\Package\Toolkit\RouteLocalizer\RouteLocalizer;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use \App\Package\Openform\Entity\News;
use \App\Package\Openform\Entity\MenuPage;
/**
* FrontUtil
*
* @author Daniel Balowski <d.balowski@openform.pl> (_creator), j.mroz
* @copyright 2019 Openform
* @since 05.2019
*/
class FrontUtil
{
function isMobileDevice()
{
return preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i" , $_SERVER["HTTP_USER_AGENT"]);
}
public function getTitleByRangePath($rangePath, $locale) {
$parts = explode('_', str_replace('|','',$rangePath));
$repo = $this->em->getRepository('Openform:'.$parts[0]);
$entity = $repo->find($parts[1]);
return $entity->getTranslation()[$locale]->getTitle();
}
public function count($locale, $filters, $filterName, $filterValue)
{
$filters = clone $filters;
foreach ($filters as $key => $row) {
if (in_array($key, ['exhibitions','museums','archives','privateCollections','rangeAllExhibition','rangeAllMuseum','rangeAllArchive','rangeAllPrivateCollection'])) {
unset($filters->$key);
}
}
$filters->$filterName = $filterValue;
$this->searchRepo = $this->em->getRepository('Openform:Search')->getFrontRepository();
return $this->searchRepo->getVisibleByFilterCount($locale, clone $filters);
}
/**
* @var EntityManager
*/
protected $em;
/**
* @var \Symfony\Component\Asset\Packages
*/
protected $assetsManager;
protected $container;
protected $request;
/**
* @var RouterInterface
*/
protected $router;
/**
* @var SessionInterface
*/
protected $session;
/**
* @var Config
*/
public $config;
/**
* @param EntityManagerInterface $em
*/
public function __construct(
EntityManagerInterface $em,
RequestStack $request,
ContainerInterface $container,
\Symfony\Component\Asset\Packages $assetsManager,
RouterInterface $router,
RouteLocalizer $route_localizer
) {
$this->em = $em;
$this->assetsManager = $assetsManager;
$this->request = $request->getCurrentRequest();
$this->container = $container;
$this->session = $request->getMainRequest() ? $request->getSession() : null;
$this->router = $router;
$this->route_localizer = $route_localizer;
}
public function getLocale()
{
return $this->request->getLocale();
}
/**
* Return , get config
*
* @return Config|null
*/
public function getConfig(): ?Config
{
if (!$this->config) {
/** @var ConfigRepository */
$repo = $this->em->getRepository(Config::class);
$this->config = $repo->createQueryBuilder('e')
->select('e')
->addOrderBy('e.id', 'ASC')
->leftJoin('e.Translation', 't')->addSelect('t')
->getQuery()->useQueryCache(true)->enableResultCache()
->getResult();
if (count($this->config)) {
$this->config = $this->config[0];
}
}
return $this->config;
}
/**
* Zwraca route pod guzik zmiany jezyka
*
* @param string $newLocale, zmiana z PL->EN, newLocale = en
* @return string
*/
public function langChangerPath(string $newLocale): string
{
$params = $this->request->get('_route_params');
if ($newLocale !== 'pl') {
$params['locale'] = $newLocale;
} else {
$params['locale'] = null;
}
$params['oldlocale'] = $this->request->getLocale();
return $this->request->get('_route') ?
$this->router->generate('changer_' . str_replace(['_default', 'changer_'], '', $this->request->get('_route')) . ($newLocale == 'pl' ? '_default' : ''), $params) : '';
}
/**
* Return imagepath by type from thumbs
*
* @param string $p, path to file
* @param string $type, eg. detail,list
* @return boolean|string
*/
public function getImagePathByType($thumbs, string $thumbType)
{
if (!$thumbs) {
return false;
}
$path = false;
foreach($thumbs as $thumb) {
if ($thumb->getName() == $thumbType) {
$path = $thumb->getFilePath();
break;
}
}
if (!$path) {
return false;
}
if (is_file('../public_html' . $path)) {
return $path;
} else {
return false;
}
}
/**
* Gets image size
*
* @param string $imagePath
*
* @return array
*/
public function getImageSize(string $imagePath): array
{
if (!is_file(__WEB_DIR__ . $imagePath)) {
return ['width' => 0, 'height' => 0];
}
list($width, $height) = getimagesize(__WEB_DIR__ . $imagePath);
return ['width' => $width, 'height' => $height];
}
/**
* Get message to Admin Operation Status Green Box
*
* @return string
*/
public function getOperationStatusOnce(): string
{
$out = $this->session->get('ADMIN_OPERATION_STATUS', '');
$this->setOperationStatus('');
return $out;
}
/**
* Set message for Admin Operation Status Green Box
*
* @param string $txt
*/
public function setOperationStatus(string $txt): void
{
$this->session->set('ADMIN_OPERATION_STATUS', $txt);
}
public function isMourning()
{
return $this->getConfig()->getIsMourning();
}
public function menuVariant()
{
return $this->getConfig()->getMenuVariant() ? 'variant' : '';
}
/**
* Get page by id
*
* @param int $id
* @return Page
*/
public function getPageById(int $id)
{
/** @var PageRepository */
$repo = $this->em->getRepository('Openform:Page');
return $repo->getOneById($id);
}
/**
* Gets page visible by idname
*
* @param string $idname
* @param string $locale
*
* @return Page|NULL
*/
public function getPageByIdname(string $idname, string $locale): ?Page
{
return $this->em->getRepository('Openform:Page')->getFrontRepository()->getByIdname($idname, $locale);
}
public function pageUrlByIdName(string $idname, string $locale, $params = [])
{
try {
return $this->route_localizer->generate($idname, $params, $locale);
} catch (\Exception $e) {
$page = $this->getPageByIdname($idname, $locale);
return $this->route_localizer->generate('page', ['slug' => $page->getTranslation()[$locale]->getSlug()], $locale);
}
}
// public function pageUrlByIdname(string $idname, string $locale, $params = [])
// {
// try {
// return $this->route_localizer->generate($idname == 'page' ? 'not_existed_route_here_make_exception' : $idname , $params, $locale);
//
// } catch (RouteNotFoundException $e) {
//
// $pageEntity = $this->getPageByIdname($idname, $locale);
//
// return $this->route_localizer->generate('page', ['slug' => $pageEntity->getTranslation()[$locale]->getSlug()], $locale);
// }
// }
/**
* Get glue string to tag <title> config.title ~ glue ~ entity.title </title>
*/
public function getMetaTitleGlue(): string
{
return ' - ';
}
/**
* Get full menu page structure, eg for sitemap
* @param string $locale
* @return array
*/
public function getFullMenu(string $locale, $parentId=false): array
{
$menu = array();
$qb = $this->em->createQueryBuilder()->select('p')
->from('Openform:Page', 'p')
->leftJoin('p.Translation', 't')
->addSelect('t')
->andWhere('p.stat = 1')
->andWhere('p.mainMenu = 1')
->andWhere('t.lang = :locale')
->andWhere('t.title IS NOT NULL')
->andWhere('t.slug IS NOT NULL')
->setParameter('locale', $locale);
if ($parentId) {
$qb->andWhere('p.Parent = :parentId')
->setParameter('parentId', $parentId);
} else {
$qb->andWhere('p.Parent IS NULL');
}
$qb->addOrderBy('p.ord', 'DESC');
$items = $qb->getQuery()->useQueryCache(true)->enableResultCache()->getResult();
foreach ($items as $item) {
$menu[$item->getId()] = array(
'title' => $item->getTranslation()[$locale]->getTitle(),
'titleHtml' => $item->getTranslation()[$locale]->getTitleHtml(),
'parent' => $item->getParent() ? $item->getParent()->getId() : 0,
'id' => $item->getId(),
'idname' => $item->getIdname(),
'slug' => $item->getTranslation()[$locale]->getSlug(),
'link' => $item->getTranslation()[$locale]->getLink(),
'blank' => $item->getBlank(),
'imagepath' => $item->getImagePath(),
'column' => $item->getMainMenuColumn(),
'children' => $this->getFullMenu($locale, $item->getId()),
);
}
return $menu;
}
public function getFootMenu(string $locale): array
{
return $this->em->createQueryBuilder('e')
->select('p, t')
->from('Openform:Page', 'p')
->leftJoin('p.Translation', 't')
->andWhere('p.stat = 1')
->andWhere('p.footMenu = 1')
->andWhere('t.lang = :locale')->andWhere('t.title IS NOT NULL')->andWhere('t.slug IS NOT NULL')
->setParameter('locale', $locale)
->addOrderBy('p.footMenuOrd', 'ASC')
->getQuery()
->getResult();
}
public function getFootMenu2(string $locale): array
{
return $this->em->createQueryBuilder('e')
->select('p, t')
->from('Openform:Page', 'p')
->leftJoin('p.Translation', 't')
->andWhere('p.stat = 1')
->andWhere('p.footMenu2 = 1')
->andWhere('t.lang = :locale')->andWhere('t.title IS NOT NULL')->andWhere('t.slug IS NOT NULL')
->setParameter('locale', $locale)
->addOrderBy('p.footMenu2Ord', 'ASC')
->getQuery()
->getResult();
}
public function getFooterMenu(string $locale): array
{
$qb = $this->em->createQueryBuilder()->select('p')
->from(Page::class, 'p')
->leftJoin('p.Translation', 't')
->addSelect('t')
->andWhere('p.stat = 1')
->andWhere('p.footMenu = 1')
->andWhere('t.lang = :locale')
->andWhere('t.title IS NOT NULL')->andWhere('t.slug IS NOT NULL')
->setParameter('locale', $locale)
->addOrderBy('p.ord', 'DESC');
$items = $qb->getQuery()->getResult();
$menu = array();
foreach ($items as $item) {
$menu[$item->getId()] = array(
'title' => $item->getTranslation()[$locale]->getTitle(),
'titleHtml' => $item->getTranslation()[$locale]->getTitleHtml(),
'id' => $item->getId(),
'idname' => $item->getIdname(),
'slug' => $item->getTranslation()[$locale]->getSlug(),
);
}
return $menu;
}
/**
* Set active page top
* @param integer $pageid
*/
public function setMenuPageActive(int $pageid)
{
$this->session->set('pagetopactive', $pageid);
}
public function getMenuPageActive()
{
return $this->session->get('pagetopactive', 0);
}
/**
* Find and set active page top, if page is children
*
* @param Page $entity
* @return void
*/
public function setMenuPageFindActive(\App\Package\Openform\Entity\Page $entity)
{
while ($entity->getId()) {
if ($entity->getParent() && $entity->getParent()->getId() > 0)
$entity = $entity->getParent();
else
break;
}
$this->setMenuPageActive($entity->getId());
}
/**
* Helper, to get repo and then use ->find, ->findAll, etc..
*
* @param string $repoClass
* @return void
*/
public function getRepository(string $repoClass)
{
return $this->em->getRepository($repoClass);
}
/**
* Return string json jako obiekt
* @return object|null
*/
public function getJsonDecode(string $obj)
{
if ($obj) {
try {
$obj = \json_decode($obj);
return $obj;
} catch (\Exception $e) {
return null;
}
} else {
return null;
}
}
// CRYPTER
public function crypter($action, $string)
{
$output = false;
$encrypt_method = "AES-256-CBC";
$secret_key = '8986395b-b8f6-4c48-8c6e-799990090902';
$secret_iv = 'fdcbcf1b-64ec-424d-942c-4e0434ea5543';
// hash
$key = hash('sha256', $secret_key);
// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
$iv = substr(hash('sha256', $secret_iv), 0, 16);
if ($action == 'encrypt') {
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
$output = base64_encode($output);
} elseif ($action == 'decrypt') {
$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
}
return $output;
}
/**
* Get mailer email from ulr defined in .env
* @return string
*/
public function getMailerEmail(string $mailerUrl): string
{
//$mailerUrl = $this->container->getParameter('app.mailer.url');
$mailerMailPosStart = strpos($mailerUrl, '://') + 3;
$mailerMailPosEnd = strpos($mailerUrl, ':', $mailerMailPosStart);
$mailerMail =
$mailerMailPosEnd !== false ?
substr(
$mailerUrl,
$mailerMailPosStart,
$mailerMailPosEnd - $mailerMailPosStart
) : substr(
$mailerUrl,
$mailerMailPosStart
);
return $mailerMail;
}
/**
* Zwraca pierwszy slide z galeri + info o ilosci zdjec i filmów w galerii
*
* @param object $gallery
* @return array
*/
public function GalleryDetail(object $gallery): array
{
$photos = $movies = 0;
$slides = [];
if ($gallery->getStat() === true) {
$slides = $this->GalleryVisibleSlides($gallery);
$photos = $movies = 0;
foreach ($slides as $s) {
if ($s->getVideoPath() || $s->getYtCode()) {
$movies++;
} else {
$photos++;
}
}
}
return ['slide' => count($slides) ? $slides[0] : null, 'movies' => $movies, 'photos' => $photos];
}
/** helper, zwraca visible slaidy z galerii */
public function GalleryVisibleSlides(object $gallery): ?array
{
if ($gallery->getStat() == 0) return [];
return $this->em->createQueryBuilder()->select('e')
->from(GalleryImage::class, 'e')->where('e.Parent = :id')
->andWhere('e.stat = 1')
->leftJoin('e.Translation', 't')->addSelect('t')
->andWhere('t.lang = :locale')
->setParameters(['id' => $gallery->getId(), 'locale' => $this->getLocale()])
->orderBy('e.ord', 'DESC')
->getQuery()->useQueryCache(true)->enableResultCache()
->getResult();
}
public function getSectionBlocks($entity)
{
if (\method_exists($entity, 'getBlock')) {
$sec = $this->em->createQueryBuilder()->select('e')
->from(\get_class($entity), 'e')
->andWhere('e.id =:id')
->leftJoin('e.Block', 'b')->addSelect('b')
->andWhere('b.Section = :id')
->leftJoin('b.Translation', 't')->addSelect('t')
->andWhere('t.lang = :locale')
->setParameters(['id' => $entity->getId(), 'locale' => $this->getLocale()])
->orderBy('e.ord', 'DESC')
->getQuery()->useQueryCache(true)->enableResultCache()
->getResult();
return count($sec) ? $sec[0]->getBlock() : [];
}
return null;
}
/**
* grupuje sekcje sliderów + zwraca sekcje stat = 1
*
* @param [type] $entity
* @return void
*/
public function getSections($entity)
{
if (\method_exists($entity, 'getBlockSection')) {
$prevtype ='';
$key = 0;
$out = [];
foreach( $entity->getBlockSection() as $sec) {
if($sec->getStat()) {
if($sec->getType() === PageSection::SECTION_TYPE_SLIDER) {
if($sec->getType() !== $prevtype ) {
$key++;
$out[$key] = [];
}
$grupped = [];
$blocks = $this->getSectionBlocks($sec);
foreach ($blocks as $block) {
$grupped[$block->getType()][] = $block;
}
$out[$key][] = [
'section' => $sec,
'grupped' => $grupped,
'all' => self::groupButtonsBlocks($blocks)
];
}
else {
$key++;
$out[$key] = $sec;
}
$prevtype = $sec->getType();
}
}
return $out;
}
return [];
}
private static function groupButtonsBlocks($blocks)
{
$res = [];
$btnBocks = [];
foreach ($blocks as $block) {
if ($block->getType() == 'btn') {
$btnBocks[] = $block;
} else {
if (!empty($btnBocks)) {
$res[] = $btnBocks;
$btnBocks = [];
}
$res[] = $block;
}
}
if (!empty($btnBocks)) {
$res[] = $btnBocks;
}
return $res;
}
public function getNewestArticles($locale, $limit = 6 )
{
$repo = $this->em->getRepository(News::class);
return $this->em->getRepository('Openform:News')->getFrontRepository()->getVisbleNews($locale, 6);
}
public function isMp3File($filePath) {
// Pobranie rozszerzenia pliku
$fileExtension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
return $fileExtension === 'mp3';
}
public function getMenuPageItems($rootEntity)
{
$repo = $this->em->getRepository(MenuPage::class);
$frontRepo = $repo->getFrontRepository();
return $frontRepo->getMenuByRootEntity($rootEntity, $this->getLocale());
}
public function getMenuPageFooterItems($rootEntity)
{
$repo = $this->em->getRepository(MenuPage::class);
$frontRepo = $repo->getFrontRepository();
return $frontRepo->getFooterMenuByRootEntity($rootEntity, $this->getLocale());
}
public function getItemsForSearch(string $entityName, string $locale): array
{
return $this->em->createQueryBuilder('e')
->select('p, t')
->from('Openform:'.$entityName, 'p')
->leftJoin('p.Translation', 't')
->andWhere('p.stat = 1')
->andWhere('t.lang = :locale AND t.title IS NOT NULL AND t.slug IS NOT NULL')
->setParameter('locale', $locale)
->addOrderBy('t.title', 'ASC')
->getQuery()
->getResult();
}
public function getLatestNews($limit, string $locale): array
{
return $this->em->createQueryBuilder('e')
->select('p, t')
->from('Openform:News', 'p')
->leftJoin('p.Translation', 't')
->andWhere('p.stat = 1')
->andWhere('t.lang = :locale')
->andWhere('t.title IS NOT NULL AND t.slug IS NOT NULL')
->andWhere('p.publishDate <= :now' )
->setParameter('locale', $locale)
->setParameter('now', date('Y-m-d 00:00:00', time()))
->addOrderBy('p.publishDate', 'DESC')
->setMaxResults(intval($limit))
->getQuery()
->getResult();
}
}